Docsity

JavaScript Cheatsheet: Understanding Variables, Objects, Functions, and Operators, Study Guides, Projects, Research of Engineering

Toggle sidebar
bg1
Note: var,let &
constare all
valid keywords to
declare variables.
The difference
between them is
covered on page 7
of this cheatsheet.
2Basic Vocabulary
Expression
A reference, value or a
group of reference(s)
and value(s) combined
with operator(s), which
result in a single value.
Variable
A named reference to
avalueisavariable.
Keyword / reserved word
Any word that is part of
the vocabulary of the
programming language is
called a keyword
(a.k.a reserved word).
Examples: var = + if for...
Operator
Operators are reserved-words that
perform action on values and variables.
Examples: +-=*in===typeof!= ...
Statement
A group of words, numbers
and operators that do a
task is a statement.
var a=7+"2";
{
{
1Seven (7) Types
1. String
2. Number
3. Boolean
4. Null
5. Undefined
6. Symbol
7. Object
- Array
- Function
"Any text"
123.45
true or false
null
undefined
Symbol('something')
{key:'value'}
[1,"text", false]
function name() { }
{
Six Primitive Types
var user ={
name: "Aziz Ali",
yearOfBirth: 1988,
calculateAge: function(){
// some code to calculate age
}
}
{
Key
These are the
keys in user object.
Value
These are the
values of the
respective keys
in user object.
Method
If a key has a
function as a
value, its called
amethod.
3Object
An object is a data type in
JavaScript that is used to store
acombinationofdataina
simple key-value pair. Thats it.
"Don't just learn JavaScript - Become a Full-Stack JavaScript Developer" https://iLoveCoding.org
iLoveCoding
JavaScript Cheatsheet
Learn JavaScript Correctly (Video course) https://ilovecoding.org/courses/js2
Page 1
< >
♥
iLoveCoding
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download JavaScript Cheatsheet: Understanding Variables, Objects, Functions, and Operators and more Study Guides, Projects, Research Engineering in PDF only on Docsity!

Note: var, let & const are all valid keywords to declare variables. The difference between them is covered on page 7 of this cheatsheet.

2 Basic Vocabulary

Expression A reference, value or a group of reference(s) and value(s) combined with operator(s), which result in a single value. Variable A named reference to a value is a variable. Keyword / reserved word Any word that is part of the vocabulary of the programming language is called a keyword (a.k.a reserved word). Examples: var = + if for... Operator Operators are reserved-words that perform action on values and variables. Examples: + - = * in === typeof != ... Statement A group of words, numbers and operators that do a task is a statement.

var a = 7 + "2";

1 Seven (7) Types

  1. String
  2. Number
  3. Boolean
  4. Null
  5. Undefined
  6. Symbol
  7. Object
    • Array
    • Function "Any text"
      true or false null undefined Symbol('something') { key: 'value'} [ 1 , "text", false] function name() { }

Six Primitive Types var user = { name: "Aziz Ali", yearOfBirth: 1988 , calculateAge: function(){ // some code to calculate age } }

Key These are the keys in user object. Value These are the values of the respective keys in user object. Method If a key has a function as a value, its called a method.

3 Object

An object is a data type in JavaScript that is used to store a combination of data in a simple key-value pair. Thats it.

iLoveCoding

JavaScript Cheatsheet Learn JavaScript Correctly (Video course) https://ilovecoding.org/courses/js < >

♥ iLoveCoding

4 Function

A function is simply a bunch of code bundled in a section. This bunch of code ONLY runs when the function is called. Functions allow for organizing code into sections and code reusability. Using a function has ONLY two parts. (1) Declaring/defining a function, and (2) using/running a function.

// Function declaration / Function statement

function someName(param1, param 2 ){

// bunch of code as needed...

var a = param1 + "love" + param2;

return a;

// Invoke (run / call) a function

someName("Me", "You")

Name of function Thats it, its just a name you give to your function. Tip: Make your function names descriptive to what the function does. Code block Any code within the curly braces { ... } is called a "block of code", "code block" or simply "block". This concept is not just limited to functions. "if statements", "for loops" and other statements use code blocks as well. Return (optional) A function can optionally spit-out or "return" a value once its invoked. Once a function returns, no further lines of code within the function run. Invoke a function Invoking, calling or running a function all mean the same thing. When we write the function name, in this case someName, followed by the brackets symbol () like this someName(), the code inside the function gets executed. Passing parameter(s) to a function (optional) At the time of invoking a function, parameter(s) may be passed to the function code. Parameters / Arguments (optional) A function can optionally take parameters (a.k.a arguments). The function can then use this information within the code it has.

iLoveCoding

JavaScript Cheatsheet Learn JavaScript Correctly (Video course) https://ilovecoding.org/courses/js < >

♥ iLoveCoding

true - 5 // - Type coercion priority order:

  1. String
  2. Number
  3. Boolean Coercion in action Does this make sense? When trying to compare different "types", the JavaScript engine attempts to convert one type into another so it can compare the two values.

7 Coercion

Operators are reserved-words that perform action on values and variables. Arithmetic .. + .. .. - .. .. * .. .. / .. .. % .. .. ** .. Assignment .. = .. .. += .. .. -= .. .. *= .. Logical .. || .. .. && .. Equality .. === .. .. == .. Conversion

  • ..
  • .. ! .. Add Subtract Multiply Divide Remainder Exponential Assign value Add then assign Subtract then assign Multiply then assign Or And Equality Equality with coercion Convert to number Convert to number then negate it Convert to boolean then inverse it Relational / Comparison .. >= .. .. <= .. .. != .. .. !== .. Increment / Decrement ..++ ..-- ++.. --.. Others typeof .. .. instanceof .. (..) ...spread-operator . ..[..] new .. delete .. ( ..? .. : .. ) Greater than or equal to Less than or equal to Not equal after coercion Not equal Postfix increment Postfix decrement Prefix increment Prefix increment Operator Precedence Given multiple operators are used in an expression, the "Operator Precedence" determines which operator will be executed first. The higher the precedence, the earlier it will get executed. Operator Associativity Given multiple operators have the same precedence, "Associativity" determines in which direction the code will be parsed. See the Operator Precedence and Associativity table here: http://bit.ly/operatortable

6 Operators^

Full list of JavaScript operators https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators

iLoveCoding

JavaScript Cheatsheet Learn JavaScript Correctly (Video course) https://ilovecoding.org/courses/js < >

♥ iLoveCoding

if (a > 0 ) { // run this code } else if (a < 0 ) { // run this code } else { // run this code } switch (expression) { case choice1: // run this code break; case choice1: // run this code break; default: // run this code (expression)? ifTrue: ifFalse; } If -else Statement: Run certain code, "if" a condition is met. If the condition is not met, the code in the "else" block is run (if available.) Conditional statements allow our program to run specific code only if certain conditions are met. For instance, lets say we have a shopping app. We can tell our program to hide the "checkout" button if the shopping cart is empty. Switch Statement: Takes a single expression, and runs the code of the "case" where the expression matches. The "break" keyword is used to end the switch statement. There are certain values in JavaScript that return true when coerced into boolean. Such values are called truthy values. On the other hand, there are certain values that return false when coerced to boolean. These values are knows as falsy values. Ternary Operator: A ternary operator returns the first value if the expression is truthy, or else returns the second value.

8 Conditional Statements

Truthy Values true "text" 72

  • 72 Infinity
  • Infinity {} [] Falsy Values false "" 0
    • 0 NaN null undefined

9 Truthy / Falsy

iLoveCoding

JavaScript Cheatsheet Learn JavaScript Correctly (Video course) https://ilovecoding.org/courses/js < >

♥ iLoveCoding

Event Loop DOM Events Timer Process HTTP Process Third-Party Process JavaScript Engine Global Ex. Context Execution Context Execution Context Call Stack Last-in - first-out Task Task Task Message Queue

12 Event Loop

There are 3 ways to create variables in JavaScript: var, let and const. Variables created with var are in scope of the function (or global if declared in the global scope); let variables are block scoped; and const variables are like let plus their values cannot be re-assigned. var a = "some value"; // functional or global scoped let b = "some value"; // block scoped const c = "some value"; // block scoped + cannot get new value

11 Ways to create a variable

iLoveCoding

JavaScript Cheatsheet Learn JavaScript Correctly (Video course) https://ilovecoding.org/courses/js < >

♥ iLoveCoding

13 Browser

Document The viewport or the section where the website is displayed is called the document of the page. https://... Window Each tab of a browser is considered the window. This is the outer most container that a web-app can access. Notice: A website opened in one tab CANNOT access the window object of another tab. Pretty cool right? The browser contains a lot of components that a Front-End Developer may need, such as Navigator, JavaScript Engine and Dev Tools. A web browser is a pretty advance piece of software which contains a lot of components. Many of these components are accessible to a web developer, so we can create complex web apps. At the same time a lot of components are kept out of reach of the web developer for security purposes. For instance, we as web developers can get access to the user's location, but we cannot get access to the user's saved passwords or browsing history. Let's see below how a browser is structured: Dev Tools JavaScript Engine HTML / CSS Processor Navigator

iLoveCoding

JavaScript Cheatsheet Learn JavaScript Correctly (Video course) https://ilovecoding.org/courses/js < >

♥ iLoveCoding

16 Built-in Objects

Date Google 'Mozilla Date' to find the docs const d = new Date('9/17/1988'); d.getDay() d.getFullYear() d.getMonth() Date.now() Milliseconds since Jan 1, 1970 Math Google 'Mozilla Math' to find the docs Math.pow( 2 , 3 ) // 8 Math.sqrt( 16 ) // 4 Math.min( 7 , 8 , 6 ) // 6 Math.max( 7 , 8 , 6 ) // 8 Math.floor(123.45) // 123 Math.ceil(123.45) // 124 Math.round(123.45) // 123 Math.random() // 0.45.. JavaScript gives us a ton of useful built-in objects to make our lives easier. The Date and Math objects are very useful on a regular basis. Take a look at some of their features on the right. Full list of builtin objects in JavaScript visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects

15 Auto Inherited Properties

String Google 'Mozilla String' to find the docs .concat() .charAt() .indexOf() .startsWith() .endsWith() .split() .slice() Number Google 'Mozilla Number' to find the docs .toFixed() .toPrecision() .toString() Boolean Google 'Mozilla Boolean' to find the docs .toString() Array Google 'Mozilla Array' to find the docs .filter() .map() .find() .every() .some() .sort() .slice() .splice() .reduce() .forEach() When you create a value in JavaScript, certain properties are automatically inherited by this value. This magic happens because every type has a constructor with a special property called prototype. All methods on the prototype gets automatically inherited by the new value created for that type. Take a look at some of of these methods on the right. const thing = "some text"; const num = 123.45;

iLoveCoding

JavaScript Cheatsheet Learn JavaScript Correctly (Video course) https://ilovecoding.org/courses/js

iLoveCoding^ Page 10

< > ♥

What is a Promise? Promise is an object that provides a useful construct when dealing with asynchronous tasks. A promise is called a "Promise" because it guarantees it will run upon success or failure of that task. Working with a promise consists of two parts; (A) Creating a promise, and (B) Using a promise. What is an Async task? An async task is one in which a third-party process is doing the task. Examples:

  • Requesting/sending data to a database
  • Requesting/sending data via HTTP protocol
  • Working with the file system of the computer

17 Promise

Note: 90% of the time you will be working with pre-existing promises. The step of "Creating a promise" would be done for you either by a library, framework or environment you are using. Examples of promises: fetch

// (B) Using a promise

p.then((res)=>{

console.log(res)

.catch((err)=>{

console.log(err)

// (A) Create a promise

const p = new Promise((resolve, reject)=>{

// Do some async task

setTimeout(()=>{

if(condition){

resolve('Successful login');

} else {

reject('Login failed');

iLoveCoding

JavaScript Cheatsheet Learn JavaScript Correctly (Video course) https://ilovecoding.org/courses/js

iLoveCoding^ Page 11

< > ♥

19 Constructor^

// Defining a Constructor function Car(make, model, year){ this.make = make; this.model = model; this.year = year; this.setMiles = function(miles){ this.miles = miles return miles; } } // Using a constructor const car1 = new Car('Toyota', 'Prius', 2016 ); const car2 = new Car('Hyundai', 'Sonata', 2018 ); // Adding method to the constructor prototype Car.prototype.age = function(){ return (new Date()).getFullYear() - this.year; } car1.age(); // 2 Rule of thumb: A) Set properties inside a constructor. B) Set methods inside the prototype property. "new" keyword The new keyword is used to create a new object (instance) from the constructor. "prototype" property prototype is a special property on every object. Properties (methods or values) attached to the prototype property get inherited to every instance of the constructor. What is a constructor? In JavaScript, a constructor is a special function that acts as a mold to create new objects. There are numerous built-in constructors in JavaScript, such as String, Number, Promise, Date, Array, Object, and many more. We can create our own custom constructors if need be. A great place to use a constructor is when you are creating multiple objects of the same kind. There are two parts to working with a constructor: (1) Defining a constructor When creating a custom constructor (2) Using a constructor with the "new" keyword

iLoveCoding

JavaScript Cheatsheet Learn JavaScript Correctly (Video course) https://ilovecoding.org/courses/js < >

♥ iLoveCoding