Get BraveBe Brave! Private, secure and fast browsing with Brave.

JS Basics

Data types

var myNumber = 24; 		// this is a number
var myString = "Julia"; 	// this is a string
var myBoolean = false; 	// this is a boolean

null - "value of nothing"
undefined - "absence of value"

var x = null;

var x;
console.log(x);
undefined

NaN – stands for “Not-A-Number” and it’s often returned indicating an error with number operations. For instance, if you wrote some code that performed a math calculation, and the calculation failed to produce a valid number, NaN might be returned.

Operator

JS comparisons between numbers will either evaluate to true or false.

Operator Meaning
< Less than
> Greater than
<= Less than or Equal to
>= Greater than or Equal to
== Equal to
!= Not Equal to

Implicit type coercion. JavaScript is known as a loosely typed language. Basically, this means that when you’re writing JavaScript code, you do not need to specify data types. Instead, when your code is interpreted by the JavaScript engine it will automatically be converted into the “appropriate” data type. This is called implicit type coercion and you’ve already seen examples like this before when you tried to concatenate strings with numbers.

Strict equality. Instead, in JavaScript it’s better to use strict equality to see if numbers, strings, or booleans, etc. are identical in type and value without doing the type conversion first. To perform a strict comparison, simply add an additional equals sign = to the end of the == and != operators.

"1" === 1

Special characters

Quotes aren’t the only special characters that need to be escaped, there’s actually quite a few. However, to keep it simple, here’s a list of some common special characters in Javacript.

Code Character
\\ \ (backslash)
\” ” (double quote)
\’ ‘ (single quote)
\n newline
\t tab

 

Modulo

Use the % (modulo) operator to determine if a number is even or odd. The modulo operater takes two numbers and returns the remainder when the first number is divided by the second one:

console.log(12 % 3); 
console.log(10 % 4);

 

Functions

There is an integrated JavaScript constructor named Function() which can be used to describe a function.

var myFunction = new Function("x", "y", "return x * y");
var z = myFunction(6, 9);
console.log(z);

These functions do not run instantly. Instead, are stored for later when they are requested upon.

function myFunction (x, y) {
  return x * y;
}
var z = myFunction(6, 9);
console.log(z);

Alternative way of declaration

var myFunction = function (x, y) 
{ 
return x * y
};
var z = myFunction(6, 9);
console.log(z);

 

Logical operators

Logical operators can be used in conjunction with boolean values (true and false) to create complex logical expressions.

By combining two boolean values together with a logical operator, you create a logical expression that returns another boolean value. Here’s a table describing the different logical operators:

Operator Meaning Example How it works
&& Logical AND value1 && value2 Returns true if bothvalue1andvalue2 evaluate to true.
|| Logical OR value1 || value2 Returns true if eithervalue1orvalue2 (or even both!) evaluates to true.
! Logical NOT !value1 Returns the opposite of value1. If value1 is true, then !value1 is false.

 

Truth tables

Before you advance any further in the lesson, here’s the truth tables for logical AND ( && ) and logical OR ( || ).

&& (AND)

A B A && B
true true true
true false false
false true false
false false false

|| (OR)

A B A || B
true true true
true false true
false true true
false false false

 

Truthy and Falsy

Every value in JavaScript has an inherent boolean value. When that value is evaluated in the context of a boolean expression, the value will be transformed into that inherent boolean value.

Falsy values:

  1. the Boolean value false
  2. the null type
  3. the undefined type
  4. the number 0
  5. the empty string ""
  6. the odd value NaN (stands for “not a number”, check out the NaN MDN article)

Truthy values

Essentially, if it’s not in the list of falsy values, then it’s truthy! Here are some other examples of truthy values:

true
42
"pizza"
"0"
"null"
"undefined"
{}
[]

Ternary operator

The ternary operator provides you with a shortcut alternative for writing lengthy if…else statements.

conditional ? (if condition is true) : (if condition is false)

To use the ternary operator, first provide a conditional statement on the left-side of the ?. Then, between the ? and :write the code that would run if the condition is true and on the right-hand side of the : write the code that would run if the condition is false.

Switch statement

switch statement is an another way to chain multiple else if statements that are based on the same value without using conditional statements. Instead, you just switch which piece of code is executed based on a value.

switch (option) {
  case 1:
    console.log("You selected option 1.");
  case 2:
    console.log("You selected option 2.");
  case 3:
    console.log("You selected option 3.");
  case 4:
    console.log("You selected option 4.");
  case 5:
    console.log("You selected option 5.");
  case 6:
    console.log("You selected option 6.");
}

Here, each else if statement (option === [value]) has been replaced with a case clause (case: [value]) and those clauses have been wrapped inside the switch statement.

Break statement

The break statement can be used to terminate a switch statement and transfer control to the code following the terminated statement. By adding a break to each case clause, you fix the issue of the switch statement falling-through to other case clauses.

var option = 3;

switch (option) {
  case 1:
    console.log("You selected option 1.");
    break;
  case 2:
    console.log("You selected option 2.");
    break;
  case 3:
    console.log("You selected option 3.");
    break;
  case 4:
    console.log("You selected option 4.");
    break;
  case 5:
    console.log("You selected option 5.");
    break;
  case 6:
    console.log("You selected option 6.");
    break; // technically, not needed
}

Increment and decrement

 The summary for different operators that can be used:
x++ or ++x // same as x = x + 1 
x-- or --x // same as x = x - 1
x += 3 // same as x = x + 3
x -= 6 // same as x = x - 6
x *= 2 // same as x = x * 2
x /= 5 // same as x = x / 5

Scope

  • If an identifier is declared in global scope, it’s available everywhere.
  • If an identifier is declared in function scope, it’s available in the function it was declared in (even in functions declared inside the function).
  • When trying to access an identifier, the JavaScript Engine will first look in the current function. If it doesn’t find anything, it will continue to the next outer function to see if it can find the identifier there. It will keep doing this until it reaches the global scope.
  • Global identifiers are a bad idea. They can lead to bad variable names, conflicting variable names, and messy code.

Hoisting

Sometimes your JavaScript code will produce errors that may seem counterintuitive at first. Hoisting is another one of those topics that might be the cause of some of these tricky errors you’re debugging. The code should be written from top to bottom always and everytime.

  • JavaScript hoists function declarations and variable declarations to the top of the current scope.
  • Variable assignments are not hoisted.
  • Declare functions and variables at the top of your scripts, so the syntax and behavior are consistent with each other.

Function Expression

When a function is assigned to a variable. The function can be named, or anonymous. Use the variable name to call a function defined in a function expression.

// anonymous function expression
var doSomething = function(y) {
  return y + 1;
};
// named function expression
var doSomething = function addOne(y) {
  return y + 1;
};

Inline function

An inline function is a function that is declared in the same place as you would place an argument, inside of the main function. An example of this would be:

function whatever(argument1, argument2) {
//code inside
//returns a value or not
}

//now for the inline function
//in this example, argument1 is used as an argument
//argument2 is turned into an inline function
//calling the inline function now

whatever(argument1, function inlineFunction() {
//write your code in here for the inline function
},); //closes the inline function.
// don't change this code
function emotions(myString, myFunc) {
    console.log("I am " + myString + ", " + myFunc(2));
}

emotions("happy", function laugh(num) {
    var funny = "";
    for (i=1; i <= num; i++) {
    funny += "ha";
}
return (funny + "!")
}
)

Array Properties and Methods

JavaScript provides a large number of built-in methods for modifying arrays and accessing values in an array, check out the MDN Documentation, or type []. into the JavaScript console for a list of all the available Array methods.

The forEach() loop

Arrays have a set of special methods to help you iterate over and perform operations on collections of data. You can view the MDN Documentation list of Array methods here, but a couple big ones to know are the forEach() and map()methods.

The forEach() method gives you an alternative way to iterate over an array, and manipulate each element in the array with an inline function expression.

var donuts = ["jelly donut", "chocolate donut", "glazed donut"];

donuts.forEach(function(donut) {
  donut += " hole";
  donut = donut.toUpperCase();
  console.log(donut);
});
Prints:
JELLY DONUT HOLE
CHOCOLATE DONUT HOLE
GLAZED DONUT HOL

Map

With the map() method, you can take an array, perform some operation on each element of the array, and return a new array.

var donuts = ["jelly donut", "chocolate donut", "glazed donut"];

var improvedDonuts = donuts.map(function(donut) {
  donut += " hole";
  donut = donut.toUpperCase();
  return donut;
});
donuts array: ["jelly donut", "chocolate donut", "glazed donut"]
improvedDonuts array: ["JELLY DONUT HOLE", "CHOCOLATE DONUT HOLE", "GLAZED DONUT HOLE"]

 

Since each row is an array of donuts, you next need to set up an inner-loop to loop over each cell in the arrays.

for (var row = 0; row < donutBox.length; row++) {
  // here, donutBox[row].length refers to the length of the donut array currently being looped over
  for (var column = 0; column < donutBox[row].length; column++) {
    console.log(donutBox[row][column]);
  }
}

 

Object-literal notation

The syntax you see below is called object-literal notation. There are some important things you need to remember when you’re structuring an object literal:

  • The “key” (representing a property or method name) and its “value” are separated from each other by a colon
  • The key: value pairs are separated from each other by commas
  • The entire object is wrapped inside curly braces { }.
var sister = {
  name: "Sarah", 
  age: 23,
  parents: [ "alice", "andy" ],
  siblings: ["julia"],
  favoriteColor: "purple",
  pets: true
};

 

Object literals, methods, and properties

You can define objects using object-literal notation:

var myObj = { 
  color: "orange",
  shape: "sphere",
  type: "food",
  eat: function() { return "yummy" }
};

myObj.eat(); // method
myObj.color; // property

Naming conventions

Feel free to use upper and lowercase numbers and letters, but don’t start your property name with a number. You don’t need to wrap the string in quotes! If it’s a multi-word property, use camel case. Don’t use hyphens in your property names

var richard = {
  "1stSon": true;
  "loves-snow": true;
};

richard.1stSon // error
richard.loves-snow // error

 

Leave a Reply