Variables and Types

Like almost every dynamic language, JavaScript is a "duck-typed" language, and therefore every variable is defined using the var keyword, and can contain all types of variables.

We can define several types of variables to use in our code:

const myNumber = 3; // a number
const myString = "Hello, World!" // a string
const myBoolean = true; // a boolean

More notes
  • In JavaScript, the Number type can be both a floating point number and an integer.
  • Boolean variables can only be equal to either true or false.
Array vs Object

There are two more advanced types in JavaScript. An array, and an object. We will get to them in more advanced tutorials.

const myArray = []; // an array
const myObject = {}; // an object

Undefined and Null

On top of that, there are two special types called undefined and null.

When a variable is used without first defining a value for it, it is equal to undefined. For example:

const newVariable;
console.log(newVariable); //prints undefined

Null

However, the null value is a different type of value, and is used when a variable should be marked as empty. undefined can be used for this purpose, but it should not be used.

const emptyVariable = null;
console.log(emptyVariable);

Functions

Functions are code blocks that can have arguments, and function have their own scope. In JavaScript, functions are a very important feature of the program, and especially the fact that they can access local variables of a parent function (this is called a closure).

There are two ways to define functions in JavaScript

  • named functions
  • anonymous functions

To define a named function, we use the function statement as follows:

function greet(name)
{
return "Hello " + name + "!";
}
console.log(greet("Eric")); // prints out Hello Eric!

other Great programming languages to study

  • HTML
  • CSS
  • Python
Objects

JavaScript is a functional language, and for object oriented programming it uses both objects and functions, but objects are usually used as a data structure, similar to a dictionary in Python or a map in Java. In this tutorial, we will learn how to use objects as a data structure. The advanced tutorials explain more about object oriented JavaScript. To initialize an object, use curly braces:

var emptyObject = {};
var personObject = {
firstName : "John", lastName : "Smith"
}