Introduction to JavaScript Programming: Variables, Conditionals, and Functions

2020-09-20 14:01:00 | #programming #javascript | Part 3 of 5

Tested On

  • Linux Ubuntu 20.04
  • Windows 10
  • macOS Catalina

Regardless of which programming language you start with, the basic building blocks are more or less the same. Programming is about creating instructions with the goal of carrying out a specific task. With just a series of inputs, outputs, and decision trees, we can produce near-infinite possibilities.

Today, we're learning how to utilize three of those building blocks, namely variables, conditionals, and function. Before you continue, please complete the prerequisites above, which will ensure you have an environment to execute JavaScript code.

JavaScript Variables

When programming, we work with a variety of data types, data sets, and collections. To do useful things with this data, sometimes, we need to store them in memory, so we can refer to and modify them, later on. In the following example, we declare some XY coordinates, in order to perform different calculations on them.

var x = 25;
var y = 50;
  
console.log(x);
console.log(y);
console.log(x, y);
console.log(x + y);
console.log(x - y);
console.log(x * 10);

As you may have noticed, we declare variables with the var keyword, the name of the variable, and then the value it equals. We don't need to explicitly set the type of value we're using because JavaScript infers that depending on how we declare the variable. JavaScript defines a Number, in the example above, when we use integers or decimal numbers. In the example below, JavaScript sets a variable type of String when we put our value in quotes. A string is just a set of literal characters. You can declare them with quotes.

var firstName = 'Jane';
var lastName = 'Doe';
    
console.log(firstName, lastName)
console.log(firstName + ' ' + lastName)

Strings and numbers behave differently when added together. Strings are literally combined, but numbers are added and return a sum. Notice that when adding a number and a string together, JavaScript first converts the number to a string, and then combines both literal strings. I advise you not to let JavaScript guess for you, as it could lead to unexpected results and produce bugs. Be explicit with variable types before you perform these operations.

var a = 25;
var b = 25;
var c = '25';
var d = '25';
    
console.log(a + b);
console.log(c + d);
console.log(a + d);

You're now familiar with Number and String. If you'd like, take a moment to get familiar some other data types:

Data Type Description String representation Example
String A sequence of literal characters string var s = 'Hello'
Number A whole positive or negative number number var x = 123
Boolean A flag set to either true or false boolean var x = true
Array An ordered, indexed, set of values (of any data type; lists can even store lists.) object var numbers = [1, 3, 4, 5]
Object A structured, key/value pair set of values object var record = {'name': 'John', 'age': 29}
Function A block of code that performs a certain task function var f = function() {}

JavaScript Conditionals

JavaScript conditional statements give you the ability to provide "conditions" and decision trees to your code, in the form of "if ... then... else". Let's try an example where we create logic for the following sentence: "if x is greater than 100, then print true to the screen, else print false to the screen."

var x = 5
if (x > 10) {
  console.log(true);
} else {
  console.log(false);
}

Now try updating the value of x to less than 10 and rerun the program. To make more complex conditionals, you can add more conditions with else if, like in the following example:

var x = 75;
if (x === 50) {
  console.log('Exactly 50');
} else if (x > 50) {
  console.log('Greater than 50');
} else if (x < 50) {
  console.log('Less than 50')
} else {
  console.log('Not an integer');
}

You can add as many else if conditions as you need. If you have a handful of specific values you need to compare against, you can write a switch statement:


var priority = 0;

switch(priority) {
  case '0':
    console.log('critical');
    break;
  case '1':
    console.log('high');
    break;
  case '2':
    console.log('medium');
    break;
  default:
    console.log('invalid')
  
}

JavaScript Comparison Operators

At this stage, you've been exposed to some new syntax, mainly === and > and <. These are called comparison operators. They allow us to compare if a value is equal to ===, greater than >, or less than < another. As a side note, we use 3 equals signs to not only compare if two values are equal, but if they're also equal data types. Use 2 equals signs when you don't care if the types match. Here are a few more operators:

Operator Description Example
=== Equal to x === y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
!== Not equal to x !== y

Feel free to experiment with these operators to create even more conditionals.

JavaScript Logical Operators

JavaScript Logical operators give us the ability to produce more complicated logic and decision trees. To check if all conditions have been met, use &&. To check if at least one condition has been met, use ||. And to check if a value is not equal to something, use !== .

var x = 75;

if (typeof x === 'number') {

  if (x % 2 === 0) {
    console.log('Even number');
  } else {
    console.log('Odd number');
  }

  if (x === 0 || x === 1) {
    console.log('Number is 0 or 1');
  } else {
    console.log('Number is not 0 or 1');
  }

  if (x % 2 !== 0) {
    console.log('Not an even number');
  } else {
    console.log('Not an odd number');
  }

} else {
  console.log('Not a number');
}

JavaScript Functions

Similarly to variables, functions/methods are reusable. But instead of storing a value, you can store code blocks into a function. Let's put our examples above into functions to make it easier to reuse them. In the following example, we move our even number checker into a function that we can invoke directly. All of the code that's indented inside the function is a part of that function. Everything else is outside.

A JavaScript method or function stores reusable functionality into a block of code that can be invoked by the function's name. So rather than write all of the code to fetch records from a database every time to need to perform that operation, you can write the logic into a function and then call the function by name— fetchRecords(), for example. Functions should be responsible for one carrying out one simple task, in order to reduce complexity and make them easier to maintain and test.

function isEvenNumber(x) {
  if (typeof x === 'number' && x % 2 == 0) {
    return true;
  } else {
    return False;
  }
}

console.log(is_even_number(2));
console.log(is_even_number(5));
console.log(is_even_number('Hello'));

JavaScript Code Commenting

Comments are phrases and sentences inside that code that does not execute. It is meants to be extra information for us and other developers, to better understand the code. Or code that we want to keep in the program, but don't want to delete. Commenting is also useful for quickly deactivating code, while debugging. Use the # symbol to turn a line of code into a comment.

Code commenting allows us add comments to our code that we or other developers may find useful. Commenting also allows us to instruct the program not to execute a line or lines of code, without having to remove the code, entirely. To create a code comment, add // before the line, or wrap multiple lines of code in /* */ characters.

// The program will ignore this line, but execute the next
console.log('Hello');

// The following code will not execute
// console.log('Goodbye');

/*
Comments can also span multiple lines
Comments can also span multiple lines
Comments can also span multiple lines
*/
  
// The following code will execute, but the comment to the right won't
console.log('Hello')  // This is an inline comment

JavaScript Programming Exercises

Try to solve the following problems, using everything you've learned up to this point. Feel free to share better solutions in the comments. Optimize each solution, as much as possible.

  1. Convert a string to a number using JavaScript

    Input: '250'

    Expected Output: 250

    var converted = parseInt('500');
    console.log(converted);
    console.log(typeof converted === 'number');
  2. Print the length of a string using JavaScript

    Input: 'The quick brown fox jumped over the lazy dog'

    Expected Output: 43

    var length = len('The quick brown fox jumps over the lazy dog');
    console.log(length);
  3. Print an integer squared with JavaScript

    Input: 5

    Expected Output: 25

    console.log(5 * 5)
  4. Print a variable's type using JavaScript

    console.log(typeof 'Hello');
    console.log(typeof 59);
    console.log(typeof 59.9);
    console.log(typeof {});
    console.log(typeof []);
  5. Write a JavaScript function that accepts a single number, and returns true if it is odd

    Input: 5

    Expected Output: true

    Input: 8

    Expected Output: false

    function isOdd(num) {
      if (num % 2 !== 0) {
        return true;
      }
    
      return false;
    }
    
    console.log(isOdd(3));
    console.log(isOdd(6));

    Notice that an else statement is not required. When an odd number is found, the function returns true immediately and breaks out of the function. For all other scenarios, it continues to the end of the function where we can just return false. Writing it this way reduces unnecessary lines of code.

    Notice how we don't need to explicitly define an else condition. Code inside a function executes every line until the keyword break or return is found. return immediately exists the function and returns the value indicated. In this case, if the number is odd, it never reaches the end of the function because true is immediately returned. In all other cases, it does reach the end and returns false .

Conclusion

We hope you found this tutorial, useful, in getting a better understanding of the JavaScript fundamentals.

If you're interested in making interactives and games, we recommend you take our Learn JavaScript While Building a Game Framework course, which teaches you JavaScript and ES6 while you build an HTML5 Canvas, physics-based framework, from scratch. You'll also learn drag and drop, mouse following, velocity, acceleration, friction, and many other useful functionality you can build interactives and games with. In addition, it compiles into a browser-compatible ES2015 build. Start making canvas applications, today.

Want To See More Exercises?

View Exercises View Courses

Comments

You must log in to comment. Don't have an account? Sign up for free.

Subscribe to comments for this post

Want To Receive More Free Content?

Would you like to receive free resources, tailored to help you reach your IT goals? Get started now, by leaving your email address below. We promise not to spam. You can also sign up for a free account and follow us on and engage with the community. You may opt out at any time.



Tell Us About Your Project









Contact Us

Do you have a specific IT problem that needs solving or just have a general IT question? Use the contact form to get in touch with us and an IT professional will be with you, momentarily.

Hire Us

We offer web development, enterprise software development, QA &amp; testing, google analytics, domains and hosting, databases, security, IT consulting, and other IT-related services.

Free IT Tutorials

Head over to our tutorials section to learn all about working with various IT solutions.

Contact