JavaScript Basics

https://github.com/devleague/prep-js-basics

JavaScript Keywords

are reserved words

Your code editor will highlight (most) keywords

highlighted as blue

Never use reserved words as variable or function names

var var = function;

function var() { 
	var true = false;
	var = true;
	var return = var;
	if( var === true ){
		return return;
	}
}

Variables

"containers" for data

really, they are Pointers (references) to data stored in Memory (RAM)

To define a new variable

use the keyword var

// define
var my_awesome_variable_name;

// access to change value
my_awesome_variable_name = "A literal value of type String";

// access to read value
console.log( my_awesome_variable_name );

// define and set value in one line
var some_numbers = [0,1,2,3,4,5];

Variable Name Rules

  • contain only alphanumeric characters,
    underscores, and dollar signs
    (no other special characters)
  • must begin with a letter, $, or _
  • are case sensitive
  • must not be a reserved word
  • cannot have any spaces

Multiple Word Variable Names

use camelCase to seperate words

var userName;
var firstName;
var lastName;

Data Types

  • String
  • Number
  • Boolean
  • Object
  • Array
  • null
  • undefined

String Data Type

Syntax for Strings

// Strings are wrapped between double quotes
"Hello World"

// or single quotes
'Hello Solar System'

// wrap literal single quotes in double quotes
"Hello Local Interstellar Cloud, i'm fine"

// wrap literal double quotes in single quotes
'Hello "Local Bubble", how are you?'

// or escape double quotes with a backslash \
"Hello Orion's \"Arm\""

// or escape single quotes with a backslash \
'Hello Virgo\'s Supercluster'

// concatenate strings
"Observble" + "universe"

// concatenate with a space
"Observble" + " " + "universe"

#1

Number Data Type

Syntax for Number

// Integer
42

// Floating Point Value
0.5432
41.9999998
8.2e+2 // 820
8.2e-4 // 0.00082

// Octal (not in strict mode)
010    // 8
012    // 10
0755   // 493

// Hexadecimal
0xf         // 15
0x10        // 16
0xDEADBEEF  // 3735928559

// Not a Number
NaN

// Infinites
Infinity
-Infinity

#2

Boolean Data Type

Syntax for Boolean

// literals
true
false

// falsy
false
0
""
null
undefined
NaN

// truthy, any other value not in the falsy list
true
1
"true"
"false"
function(){}
[]
{}

#3

Null Data Type

has only one value, null

and it's type is Object

// literal
null

// set a previous value to no value
var empty = "mind";
empty = null;
empty === null  // evaluates to true

#4

undefined Data Type

when a variable doesn't exist, or hasn't been set

// literal
undefined

// create a variable with no value
var zed;
zed == undefined            // true
typeof(zed) === "undefined" // true

Arrays

Zero-based Index Storage

[]

Arrays

can store any data type inside of it.

Arrays are defined by the []

 

Arrays are zero-based index. Meaning the first value in an array is 0 and increments by 1 for each place after.

 

Arrays have methods that help you modify or access values within the array.

["Burger", "Burrito", "Sammich"]

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

["Burger", 231, {name: "Ray"}, null, undefined, []]

Accessing Values

#5


var favoriteFoods = ["Burger", "Burrito", "Sammich"];

console.log( favoriteFoods[0] ); // "Burger"

var favoriteNumbers = [3, 56, 8, 0, 19];

console.log( favoriteFoods[ ? ] ); // ??

use bracket access notation

JavaScript Operators

+      Addition

-       Subtraction

*      Multiplication

/       Division

%     Modulus

++    Increment

--      Decrement
 

Arithmetic

#6a

JavaScript Operators

==       equality

===     strict equality

!=        inequality

!==      strict inequality

&&      logical AND

||        logical OR

Comparison and Logic

>         greater than

<         less than

>=       greater than or equal to

<=       less than or equal to

#6b

JavaScript Operators

=     Assignment 

+=   Increment and Assign

-=    Decrement and Assign

*=   Multiply and Assign

/=    Divide and Assign

%=  Modulo and Assign

Assignment

#6c

Remember

= is for assignment

== and === are for comparing equality

Caveats

What happens when you do the following?

var mystery = "Bacon" + "Pancakes";
console.log(mystery); // ??
"BaconPancakes"

Using + with Strings will always result in a String as the final value.

var numberString = "Remember, Remember, The " + 5 + "th of November";
console.log( numberString ); // ??
"Remember, Remember, The 5th of November"

Functions

define a block statement to execute

Invoking

grabs the flow of control to execute the defined block statement

function doesNothing(){ }
doesNothing();

Functions

// function declaration
function greeting(){
  console.log("Hello World");
}

// assigning function expression to a variable
var greeting = function(){
  console.log("Hello World");
}

there are more but this is enough to server as a base

Arguments and Parameters

parameters are defined in order

only live within the scope of the function

must be a valid variable name

// declaring a function with two parameters
function add( a, b ){
  return a + b;
}

// invoking the add function with two arguments
add( 1, 2 );  // 3

// assigning the return value of the function to a value
var sum = add( 1, 2 );

Return values

// not all functions return a value
function greeting(){
  console.log("Hello World");
}

// functions can only return one time
// then "exits" the function
function createGreeting( name ){
  return "Hello " + name;
  return "Goodbye"; // function already returned, exited
  console.log("I will never execute"); // this is true
}

// conditional return
function createGreeting( name, age ){
  if( age < 32 ){
    return "Hello " + name;
  }else{
    return "Hello Mr. " + name;
  }
}

#7

Objects

collection of key value pairs

{}

Literal Objects

aka, Anonymous object

aka, Hash Table

aka, Associative Array

aka, Dictionary

// wrapped in open and closing curly braces
var basic_syntax = {};

// keys seperates value pairs separated by colons
var user = { name : "Jon" };

// keys can have special characters
var student = { "first & last name" : "Finn Human" };

// key value pairs are separated by commas
var color = {
  red : 0,
  green : 0x33,
  blue : 0xFF,
  getRGB : function(){
    return (this.red << 16) + (this.green << 8) + this.blue
  }
};

Accessing Object Properties

// access the "green" property of the "color" object
// using dot notation
color.green    // 51


// as an associative array using array accessor square brackets 
color["green"] // 51


var propertyName = "green";
color[propertyName]  // 51

Assigning values to properties

var person = {};

person.name = "Ray";

console.log( person ); // { name: "Ray" }
var person = {
    name: "Ray"
};

Why?

Object may have been passed to you

function isLiving(human) {
    human.isLiving = true;

    return human;
}

var person = { name: "Ray" };

var updatedPerson = isLiving(person);

console.log( updatedPerson ); // { name: "Ray", isLiving: true }


JavaScript Expressions

produce a value and can be written wherever a value is expected.

// expressions produce a value
true         // true
2 + 3        // 5
5 < 10       // true
add( 2, 3 ); // 5
function( base, increment ){}  // [Function]

// can be used as an argument in a function call
add( 2, 4*2 );  // 10

// or in an if statement
if( add( 2, 4*2 ) === 10 ){
  // true
}

Control Flow

the order that JavaScript interprets your code

// normal control flow
var foo = 1;
var bar = 2;
console.log( foo );  // 1
console.log( bar );  // 2
console.log( 3 );    // 3
console.log( 4 );    // 4

Control Flow

the flow of control can be manipulated

// drop in to function execution
function thief(){
  console.log( bar );  // 2
  console.log( 3 );    // 3
}

var foo = 1;
var bar = 2;
console.log( foo );  // 1
thief();  // takes control
// resume control
console.log( 4 );    // 4

Control Flow

the flow of control can be conditional

var bar = 2;
console.log( foo );  // 1
if( foo > 100 ){ // block statement does not run
  console.log( bar );
  console.log( 3 );
}
console.log( 4 );  // 4

Control Flow

the flow of control can be repeated

// for loop
for( var i=0; i<3; i++ ){
  console.log( "statement "+i+" repeats 3 times" );
}

// while loop
var i = 0;
while( i < 3 ){
  console.log( "statement "+i+" repeats 3 times" );
  i++;
}

// do while loop
var k = 3;
do{
  console.log( "statement "+k+" runs once" );
  k++;
}while( k < 3 );

Exception Handling

normal flow is disrupted by an error

// try will run execute the block statement
// and exit as soon as an exception is thrown
var humans = { pewDiePie : "PewDiePie" };
try{
  console.log("Attack pewDiePie");
  delete humans.pewDiePie;
  console.log("woot!");
}catch(error){
  console.log("You cannot kill "+humans.pewDiePie);
}

// catch will execute the block statement
// if try throws an exception
var chuckNorris = "Chuck Norris";
try{
  console.log("Attack chuckNorris");
  chuckNorris.kill();
  console.log("woot!");
}catch(error){  // handle the exception
  console.log("You cannot kill "+chuckNorris);
}

Throwing Errors

var humans = { pewDiePie : "PewDiePie" };

// throw your own exceptions
function kill( humanName ){
  if( humanName === "Chuck Norris" ){
    throw (new Error("You cannot kill "+humanName));
    // exits function block statement
  }
  delete humans[humanName];
  console.log("killed "+humanName);
}

try{
  kill("pewDiePie");
  kill("Chuck Norris");
  console.log("woot!");
}catch(error){
  console.log(error.message);
  // do something more useful, like run away!
}

js-basics (Dev League Prep)

By Ray Farias

js-basics (Dev League Prep)

Data Types, Control, Loops

  • 4,486