Skip to content

Instantly share code, notes, and snippets.

@nifl
Created April 3, 2014 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nifl/9959372 to your computer and use it in GitHub Desktop.
Save nifl/9959372 to your computer and use it in GitHub Desktop.
JS Primitives, Variables, and Operators

Primitives

  • String
  • Number
  • Boolean
  • Undefined
  • Null

Variables

Variables can't start w/ numbers or special characters except _ and $.

Creating variables

var year; // initialized w/o value (undefined)
var year = 2011; // initialized and set (defined)
  • var is not required when setting variables but is a best practice.
  • variables are case-sensitive

create multiple variables w/ comma separation

var year, month, day; 
var year=2011, month=10, day=31;

Operators

Standard operators

  • Equal == or ===

== does type coercion (conversion) before checking for equality; and === does strict equation which requires values to have the same type as well.

0 == false          // true
0 === false         // false, because they have different types (int, bool)
1 == "1"            // true
1 === "1"           // false, because they have different types (int, string)
null == undefined   // true
null === undefined  // false
  • Or ||

  • And &&

  • Not !

  • GT >

  • LT <

  • Modulo % returns the remainder of one number divided by another. e.g., 14 % 3 === 2

It's useful to test divisibility. The result of 0 indicates perfect divisibility.

Ternary Operators

Ternary operators are used as conditional shortcuts. The syntax is: condition ? result1 : result2;

The following examples are equivalent.

result = x > y ? 'good job' : 20;
if (x > y) {
  result = 'good job';
} else {
  result = 20;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment