Basic Syntax: Types and Operators

Exploring JavaScript data types and the operators used to manipulate them.

Scroll down...

Content

Resources

Comments

In this brief lesson, you'll learn the very basics of JavaScript data types and other core aspects of the language. We'll cover everything from the low-level basics to full-fledged objects and provide a glimpse of Arrays and Functions.

YAGNI and Codecademy

There's an important principle in software engineering called YAGNI, short for "You Ain't Gonna Need It." This principle steers us away from superfluity and redundancy. It is in the spirit of YAGNI that we are going to delegate a small portion of your education to the fine folks at Codecademy. Their interactive code editor is truly top-notch. While their coding-with-training-wheels approach is not ideal for all stages of learning, it will guide you safely through your initial experiences with JavaScript.

Each lesson in this section will ask you to first complete an exercise in Codecademy's interactive primer before returning here for some more in-depth examples and explication. This will give you a chance to get a feel for writing JavaScript in a safe environment, sterilized against the many bugs and edge cases which can plague real-world programming. You will be better prepared to eventually step out on your own, like when it comes time to complete your first assignment at the end of this section.

The First Codecademy Exercise

So, as we just mentioned, it is now time to go out and try your first Codecademy exercise. Go forth and complete their Introduction To JavaScript section and then hustle on back for some review.

Basic Nuts and Bolts

In general, you'll find that JavaScript shares some basic syntax conventions with CSS.

Comments

// This is an example of a single-line comment.

/*
 * this is an example
 * of a
 * multi-line
 * comment.  Seems CSS-ish, no?
 */

Whitespace

Whitespace is ignored by JavaScript. That lets you include lots of it to make your code more readable, using the indentation standards you already know:

var foo = function(){
  for( var i = 0; i < 10; i++ ){
    // do stuff
  }
}

Semicolons, Parentheses, and Braces

JavaScript is strict about things like using semicolons, parentheses, and braces. You'll see lots of these.

JavaScript requires semicolons, and though most implementations automatically add them for you at the end of every new line and so technically don't require them, you should get into the habit of putting them at the end of each line.

Whenever you start a new block in JavaScript (like functions, loops, and conditionals), you'll need to put that within curly braces. When calling functions, parentheses are required!

var foo = function(){
  for( var i = 0; i < 10; i++ ){
    console.log(i);
  }
}

Variables

Variables are declared using the var statement. You can name variables using any words that aren't reserved. The most common convention is to use Camel Case with the first letter lowercase.

You can declare multiple variables at once:

// Best
var myAwesomeVariable = "a";

// The Rest
var myAwesomeVariable2 = "b";
var my_awesome_variable = "c";
var $my_AwesomeVariable = "d";
var _my_awesome_variable_$ = "e";

// Multiple at once
var foo = 1,
    bar = function() { ... },
    baz = "BAZ!";

You can assign a variable without providing it with a value. This makes the variable undefined.

var x;
x === undefined; //=> true

There's a state in JavaScript called null -- it means that there is the absence of value. undefined isn't quite the same -- it means we haven't assigned a variable to anything. Essentially null is "intentionally void" and undefined is just "unassigned". Both are falsy.

Output

If you want to see something printed to the console, use the console.log statement. If you want it to appear in a pop-up, use an alert. Both of these will be useful for debugging:

// log to the console
console.log("Hello, world!");
//=> "Hello, world!"

// pop up into an alert
alert("Hello, world!");

Primitive Types

Primitive types will not surprise you much:

// strings can be double or single quotes
var a = "I am a string";
var b = 'So am I!';

// Strings are immutable.
var str = "hello";
str[2]; // Retrieve a letter from an index.
//=> "l"
str[2] = "z";  // try to set it to something else...
//=> "z"       // ...did it work??
str;
//=> "hello"   // ...nope.

// Numbers are all just "Number".
// Unlike many other languages
// they don't differentiate
// floats and integers
var num1 = 100;
var num2 = 100.10;
var num3 = 0.10;

// Booleans are straightforward:
var truthy = true;
var falsy = false;

// showing off undefined values
var nowUndefined;               //=> undefined
var alsoUndefined = undefined;  //=> undefined

Objects

Everything in JavaScript is an "object", which should be pretty familiar to you. A basic "object" resembles a sort of dictionary-like structure -- it's declared with squiggly braces {} and its items are a comma-separated list of key-value pairs:

  • Its keys are always strings, although you can omit the usual double quotes when assigning properties inside of the curly braces.
  • Its values can be any primitive data types but also other objects and even functions. You'll see this below.

You can get or set its items using either bracket-notation or dot-notation—you will see the difference below.

Objects in JavaScript are used everywhere and they're both simple and very useful. It's well worth your time to take a minute to work through the examples below, even playing with them in your own console or on JS Bin, to ensure you understand what's going on.

Let's say it again -- JavaScript is basically built entirely using objects. Everything is created by nested things inside of objects.

Check out the syntax:

// Using an empty object literal
var person1 = {};

// Creating an object with the object literal syntax:
var person2 = {
  firstName: "Jane",
  lastName: "Doe"
};

// Assign properties using "dot notation"
person1.firstName = "John";
person1.lastName = "Doe";

// Access properties using "dot notation"
alert( person1.firstName + " " + person1.lastName );

// Assign properties using "bracket notation"
// As mentioned, objects can also have objects as a property value
var people = {};
people[ "person1" ] = person1;
people[ "person2" ] = person2;

// Access properties using a mix of both bracket and dot notation
// Here we're digging into the enclosing object and then
// we access the property of the object within it
// You've done this countless times
alert( people["person1"].firstName );
alert( people["person2"].firstName );

// Accessing a nonexistent property returns `undefined`
people["someOtherPerson"]  //=> undefined

// Below is an object that contains a function we
// define right there (which we'll talk about
// in the lesson on functions)
// Note that we're also using naked text as
// identifiers (e.g. `sayHello` and `lastName`)
// where you'd normally suspect that only a
// string would work.  It's almost like
// setting the function to a variable... and,
// for objects, it's interchangeable with a
// string.
// You call it the same way -- both
// can be called bracket-style or dot-notation style
var myObject = {
  sayHello: function() {
    console.log( "hello" );
  },
  someObject: {
    // Using a string key
    "sayGoodbye": function() {
      console.log( "goodbye" );
    }
  },
  // Using a string key
  "firstName": "Foo",
  // Using an identifier key
  lastName: "Bar"
};

// call the string key
myObject["firstName"];      //=> "Foo"
myObject["lastName"];       //=> "Bar"

// call the standard key
// (See? It doesn't matter how you call it)
myObject.firstName;         //=> "Foo"
myObject.lastName;          //=> "Bar"

// Now call that first function
// Note that we're running the function
// so need to use parentheses
myObject.sayHello();        //=> hello

// Dig into the object-within-the-object
// and again, see that it doesn't matter
// whether you use bracket-style or
// dot-notation style of indexing into
// the object.
myObject["someObject"].sayGoodbye(); //=> goodbye
myObject.someObject.sayGoodbye();    //=> goodbye

// if you don't use parentheses, it just
// returns the function itself
myObject.sayHello;
//=>  function () {
        console.log( "hello" );
      }

Read more about JavaScript objects at MDN.

Arrays

Arrays are pretty straightforward containers for other objects. You will most commonly interact with them by either pushing values onto them, popping values off of them, or checking their length. We will examine arrays more closely in an upcoming lesson.

// Creating an array with the constructor:
var foo = new Array;

// Creating an empty array with 10 undefined slots
var bar = new Array(10)
bar.length                //=> 10
bar[3]                    //=> undefined

// Creating an array with the array literal syntax:
var bar = [1,2,3];


// "Push" items into the array
// Note: Returns the length of the array!
var baz = [];
baz.push(123);
//=> 1

// "Pop" that item from the array
// Notice the parentheses!!
baz.pop();
//=> 123

// Unshift an item into the FRONT of the array
arr = [1,2,3,4]
arr.unshift(5)
arr
//=> [5,1,2,3,4]

// Shift the item off of the FRONT of the array
arr.shift()
// => 5
arr.shift()
// => 1

See arrays docs for more, though we'll cover them deeper in a later section.

Testing Type

What if you want to know what something is (so you can compare it to something else, for instance)? Use typeof. Note, though, one common source of confusion -- arrays are the type Object!

// Testing the type of various variables.
var myFunction = function() {
    console.log( "hello" );
};
var myObject = {
    foo: "bar"
};
var myArray = [ "a", "b", "c" ];
var myString = "hello";
var myNumber = 3;
var myRegExp = /(\w+)\s(\w+)/;

typeof myFunction; // "function"
typeof myObject;   // "object"
typeof myArray;    // "object" -- Careful!
typeof myString;   // "string"
typeof myNumber;   // "number"
typeof null;       // "object" -- Careful!
typeof undefined;  // "undefined"
typeof meh;        // "undefined" -- undefined variable.
typeof myRegExp;   // "function" or "object" depending on environment

Gotchas

Some things worth remembering:

  • undefined is conceptually different than null. They represent different things (undefined - absence of a value, null - intentional void value). However, when comparing them: undefined == null will yield true. This is because how == works in JavaScript. If you want to differentiate including type, use === like so: undefined === null, which will yield false.
  • Parentheses and brackets are always needed.
  • Explicitly declare your variables with var or they'll be attached to the global scope.
  • JavaScript functions allow you to pass any number of variables and they will just ignore the extra ones.
  • To actually run a function, you need to pass it either any required arguments or no arguments at all by using the parentheses, e.g. [123].pop() instead of [123].pop which actually returns the pop function itself.

Basic Operators

Operators are essentially functions behind the scenes, but they’re sprinkled with some syntactic sugar, allowing you to space them out and call them without dots and parentheses. These basic operators tend to be the same across many programming languages.

// Concatenate strings with addition
"hello" + " " + "world";     //=> "hello world"

// Or concatenate string using
// the native concat() function
"Hello".concat(" World!");  // => "Hello World!"

// You can also concatenate strings
// using the array.join() method
// with an argument of ''
['Hello', ' World!'].join('');  // => "Hello World!"

// Addition
1 + 2                 //=> 3

// Subtraction
1 - 2                 //=> -1

// Multiplication
2 * 3;                //=> 6

// Division -- remember, everything is a float!
2 / 3;                //=> 0.6666666666666666

// Incrementation
var i = 1;
i++;
i;                    //=> 2

// The number gets turned into a string
"2" + 1;              //=> "21"

// ...unless you force the string to be a number
// by "Casting" it with the `Number` function
// or the `+` operator
Number("2") + 1;      //=> 3
+"2" + 1;             //=> 3

Logical Operators

Boolean operators combine a series of statements into a single boolean output, just like how arithmetic operators combine numbers into a single number. It’s important to realize that everything in JavaScript will evaluate to being either truthy or falsy, not just true and false.

Here’s a full rundown of falsy values, they’re an odd bunch, but they’re worth eventually committing to memory.

false // clearly
0
NaN // Not A Number
"" // Yeah, empty strings are false.
undefined
null

Now let’s take a look at how to combine these values. The and (&&) operator will return true only if both arguments evaluate to true. The or (||) operator will return true if either of its arguments is true.

Both operators will skip evaluating the right-hand argument if they can surmise their response from the left-hand argument. If the first argument to && is falsy, then it clearly must return a falsy value, so it doesn’t even bother with evaluating the second argument. Likewise, if the first argument to || is truthy, it will safely return a truthy value early. The actual return value, whether truthy or falsy, is the value of the side where the decision is made (see the examples below).

var zero = 0;
var one = 1;
var two = 2;

function someFunction() {
  console.log( "I'm evaluated!" );
};

// returns 1, which is true
one || zero;

// returns 1, which is true
zero || one;

// returns 0, which is false
one && zero;

// returns 2, which is true
one && two;

// returns 1, which is true
two && one;

// evaluates the function
zero || someFunction();

// does not evaluate the function
one || someFunction();

// evaluates the function (but don't worry about ~~ now)
~~ one && someFunction();

// does not evaluate the function
~~ zero && someFunction();

Comparison Operators

var one = 1;
var zero = 0;
var strOne = "1";
var two = 2;

// `==` checks for simple equality
one == zero; // false
one != zero; // true
one == strOne; // true; but note that the types are different

/// `===` checks whether the types are the same too
one === strOne;             // false
one !== strOne;             // true
one === parseInt( strOne ); // true
one === Number( strOne );   // true

one > two;  // false
two > strOne;  // true
one <= strOne; // true

See the docs for more.

You Can't Override Operators

Even though they behave a lot like functions, the operators are stuck the way they are. You can't make up your own + function or override Array's [] operator to do whatever you want. Sorry... :(

Code Review

The important bits of code from this lesson

// \*\*\* THE BASICS \*\*\*
// This is an example of a single-line comment.

/*
 * this is an example
 * of a
 * multi-line
 * comment.  Seems CSS-ish, no?
 */

// Whitespace is all good and
// parentheses/brackets are needed everywhere
var foo = function() {
  for( var i = 0; i < 10; i++ ) {
    console.log(i);
  }
}

// Best way to name a variable
var myAwesomeVariable = "a";

// Other valid ways to name a variable
var myAwesomeVariable2 = "b";
var my\_awesome\_variable = "c";
var $my\_AwesomeVariable = "d";
var _my_awesome_variable_$ = "e";

// Multiple assignments at once
var foo = 1,
bar = function() { ... },
baz = test2(test);

// Undefined
var x;            //=> undefined
x === undefined;  //=> true

// strings can be double or single quotes
var a = "I am a string";
var b = 'So am I!';

// numbers are all just "Number"
// so they don't differentiate
// floats and integers
var num1 = 100;
var num2 = 100.10;
var num3 = 0.10;

// Booleans are straightforward:
var truthy = true;
var falsy = false;

// showing off undefined values
var nowUndefined;
var alsoUndefined = undefined;

// \*\*\* OPERATORS \*\*\*
// Concatenate strings with addition
"hello" + " " + "world";     //=> "hello world"

// Or concatenate string using
// the native concat() function
"Hello".concat(" World!");  // => "Hello World!"

// You can also concatenate strings
// using the array.join() method
// with an argument of ''
\['Hello', ' World!'].join('');  // => "Hello World!"

// Addition
1 + 2                 //=> 3

// Subtraction
1 - 2                 //=> -1

// Multiplication
2 \* 3;                //=> 6

// Division -- remember, everything is a float!
2 / 3;                //=> 0.6666666666666666

// Incrementation
var i = 1;
i++;                  //=> 2

// The number gets turned into a string
"2" + 1;              //=> "21"

// "Cast" with the Number or + functions
Number("2") + 1;      //=> 3
+"2" + 1;             //=> 3

// Lazy evaluated comparisons
1 || 0;               //=> 1
0 || 1;               //=> 1
1 && 0;               //=> 0
1 && 2;               //=> 2

// evaluates the function
0 || someFunction();

// == checks for simple equality
1 == 0;             //=> false
1 == 1;             //=> true

// === checks whether the types are the same too
1 === "1";          //=> false
1 === Number("1");  //=> true

Wrapping Up

There shouldn't have been too much to surprise you here... just remember your semi-colons, parentheses, and brackets and you'll be fine.



Sign up to track your progress for free

There are ( ) additional resources for this lesson. Check them out!

There are no additional resources for this lesson just yet!

Sorry, comments aren't active just yet!

Next Lesson: Basic Syntax: Functions