Browser (chrome) shortcuts:
Ctrl+Shift+I : Open “Elements” tab in dev tools
Ctrl+Shift+J : Open “Console” tab in dev tools
Running JavaScript:
-
We can run JS on the browser’s console by which we will have access to the page we are on.
-
Also we can run it in a
script
tag:
<script>console.log('Heyyy');</script>
Always try to have your script
tag before the closing body
tag, because we can access the HTML elements written above the script
tag as they are above the JS.
- Also, we can run JS in another file using
script
tag withsrc
attribute:
<script src="relative path to js file"></script>
- Also we can run it via Node.js - instead of running in the context of a website we run it in an actual machine. In console, run:
node file.js
Variables and statements
Semicolons used to end a statement. You can choose to not write them (because there is ASI: Automatic Semicolon Insertion in Javascript).
Declaring a variable:
var first = 'Soumya';
let first = 'Soumya';
const first = 'Soumya';
(here value is ‘Soumya’)
-
let
andconst
were introduced in ES6 (newer). -
var
andlet
can be updated but notconst
.
var x = 'hey';
y = 'hi';
let cool = true;
cool = false;
const age = 10;
age = 11; // wrong: throws error
- In strict mode, we have to define a variable first before assigning a value to it.
dog = 'snickers'; // bad coding, don't do this
console.log(dog); // snickers (no error)
'use strict';
dog = 'snickers'; // error: dog is not defined
-
If we write
var dog;
dog is undefined. -
Scoping:
-
var : function scoped (only available inside parent functions)
-
let and const : block scoped (available inside a block denoted by { } )
-
Opinion (what to use): Use
const
by default; if the value of the variable needs to change then uselet
. Almost never usevar
. -
Variable naming conventions:
-
Should not start with capital unless they are a class.
-
Must start with a-z or _ or $.
-
If a variable is multi-word, you can use:
-
Camel-case:
let iLovePizza = true;
-
Upper Camel case (in case of classes):
ILovePizza
-
Snake case:
let i_love_pizza=true;
Code Quality Tooling
-
We use ESLint and Prettier.
-
ESLint: Javascript linting tool for identifying and reporting potential issues in code. e.g. bad practices and design patterns.
-
Prettier: Formats code.
Types
SNOBUS’N
-
String
-
Number
-
Object
-
Boolean
-
Undefined
-
Symbol : Always gives a guaranteed unique identifier
-
Null
Everything except Object is Primitive type, Object is special one.
String
-
used for holding text
-
3 ways to create strings:
- using single quotes:
const first = 'Soumya';
- using double quotes:
const middle = "Ranjan";
- using backticks:
const last = `Mohanty`;
- single quotes and double quotes are the same thing.
used for: "she's cool"
or escaping: 'she\\'s cool'
- backticks:
const sentence = `she's so "cool"`;
console.log(sentence); // she's so "cool"
- Multi-line string:
const song = 'Oh \\
I like \\
pizza';
console.log(song); // Oh I like pizza
const song = `Oh
I like
pizza`;
console.log(song);
/*
Oh
I like
pizza
*/
2nd one using backticks is mostly used.
-
String concatenation and interpolation
-
‘+’ is used for concatenation. It is also used for adding 2 nos.
-
Concatenation: when 2 or more strings combined to one
-
Interpolation: when you put a variable inside a string
-
Example 1:
const name = 'Soumya';
const hello = 'Hello my name is ' + name + '. Nice to meet you.'
(can use double or single quotes)
- Example 2:
1+1 // 2
'1'+'1' // 11
1 + '1' // 11
- Example 3:
const name = ‘Soumya’; const hello = Hello my name is ${name}. Nice to meet you. I am ${100+1} years old.
; console.log(hello); // Hello my name is Soumya. Nice to meet you. I am 101 years old.
-
Backticks also used for tagged template literals.
-
Backticks are helpful for creating HTML:
const html = `
<div>
<h2>Hey everyone! I am ${name}.</h2>
</div>
`;
Number
Only one type of number in JavaScript whether it has decimal point or not.
const age = 100;
const money = 1000.50
console.log(typeof age); // number
console.log(typeof money); // number
-
typeof
is used to find out the ‘type’ of a variable. -
Various operations: addition, subtraction, multiplication, division can be done with nos.
-
Example
"10" * "10" // 100 (number) - converts the strings to number
The above works with multiplication, division and subtraction and not addition, because the + sign is also used for concatenation.
-
Math helper methods:
-
Math.round, Math.floor, Math.ceil, Math.random and many others
Math.round(2.5); // 3
Math.floor(2.4); // 2
Math.ceil(2.4); // 3
Math.random(); // 0.565262543048269 - random no. between 0 and 1
- Modulo and Power operators:
const smarties = 20;
const kids = 3;
const eachKidGets = Math.floor(smarties/kids); // 6
const leftSmarties = smarties % kids; // 2 - modulo operation
const x = 2 ** 3; // 8 - power operation using power operator (**)
// or
const x = Math.pow(2,3); // 8 - power operation using Math.pow
- Example
0.1 + 0.2 // 0.30000000000000004
Why? Explanation
So, when working with money, don’t store them as dollars and cents. Store all of the money in cents as you won’t have to deal with fractions only whole nos. When need to display to user, just convert them back.
- Infinity and Negative Infinity:
typeof Infinity; // number
typeof -Infinity; // number
- Not a Number (NaN):
10 / 'dog' // NaN
typeof NaN // number
Object
-
Everything in JavaScript is an Object.
-
Objects are used for collection of data, collection of functionality.
-
Example:
const person = {
name: 'Soumya', // property: value
age: 100
};
typeof person // object
person.age = 101;
console.log(person.age); // 101
.
-
Order of properties doesn’t matter in an object.
-
Accessing properties:
-
person.name // Soumya
(dot notation)
Null and Undefined
-
Used to express ‘nothing’ in JavaScript.
-
If we declare a variable, and don’t set anything to it, then it has value
undefined
.
let dog;
console.log(dog); // undefined
When we try to access a variable that is created but not defined/set a value, we get undefined
.
- null: value of nothing
const somethingNull = null;
// we have explicitly set the value to be nothing with null
Booleans and Equality
-
A boolean variable can be either
true
orfalse
. -
Example:
const age = 18;
const ofAge = age > 18;
console.log(ofAge); // false
-
Equal signs:
-
=
sign: used for assignment/ updation of values
let name = 'Soumya';
name = 'Raja';
-
Out of
==
and===
, you should almost always use===
. -
==
and===
are used for equality comparison.
console.log(age === 18); // true
==
vs===
:
===
checks both type & value.
==
only checks value.
10 === "10" // false as values are same but types are not
10 == "10" // true as values are same
Functions - Built in
-
Function allows us to group together multiple statements, take in some values, perform some operations and return some value.
-
Functions take in data known as arguments.
-
Function may or may not return a value.
-
Example:
Math.max(10, 12); // 12
The above line is a JavaScript statement.
10 and 12 passed to the function are arguments, separated by comma.
12 is returned from the function.
- There are many in-built JavaScript functions.
e.g:
-
console.log('hey');
returnsundefined
, logshey
. -
parseFloat('2.032565') // 2.032565
(converts string to number) -
parseInt('2.032565') // 2
(converts string to number as integer) -
Many date functions are also present. e.g.
Date.now()
returns no. of milliseconds since January 1, 1970 00:00:00 UTC. -
DOM functions:
-
Example:
<body>
<p>Hey How ya doin?</p>
<script>
const para = document.querySelector('p'); // finds p tag in page
console.log(para); // <p>Hey How ya doin?</p>
</script>
</body>
-
Mobile only functions e.g.
navigator.vibrate()
-
In case of doubts, always refer MDN Docs.
-
Other Examples:
scrollTo(0, 200); // scrolls to (x, y) position in page
scrollTo({
top: 500,
left: 0,
behavior: 'smooth'
}); // scrolls to position top: 500, left: 0 in a 'smooth' manner
The scrollTo
function returns undefined
.
Functions - Custom
-
Functions are created/ defined then they are called.
-
Defining a function:
// Function definition
function calculateBill() {
// this is the function body
console.log('running calculateBill');
}
- Calling a function:
// Function call or run
calculateBill(); // running calculateBill (returns undefined)
- Variables created inside a function are not available outside the function. e.g.
total
above.
It is a temporary variable. After running of the function is complete, the variable is cleaned up or garbage-collected.
- Returning value from function:
function calculateBill() {
const total = 100 * 1.13;
return total; // total is returned
}
calculateBill(); // returns 112.999999999
- Capturing returned value from a function into a variable:
const myTotal = calculateBill();
(myTotal will have value 112.999999999)
Functions - arguments and parameters
-
Parameters are like placeholders for data that will be passed to a function.
-
Arguments are the actual values passed to a function while calling it
function calculateBill(billAmount, taxRate) { // here billAmount, taxRate are parameters const total = billAmount + billAmount * taxRate return total; }
calculateBill(100, 0.13); // here 100, 0.13 are arguments
-
Parameters are variables local to the function; available only inside the function.
-
You can also pass variables as arguments during a function call.
-
We can also pass expressions as arguments to a function.
myTotal3 = calculateBill(20+20+30, 0.3);
-
So, we can either pass direct value or variables holding value or expressions resulting in a value to a function as arguments.
-
Passing functions as arguments:
function doctorize(name) {
return `Dr. ${name}`;
}
function yell(name) {
return `HEY ${name.toUpperCase()}`;
}
// We can pass a function inside another
yell(doctorize("Soumya")); // HEY DR. SOUMYA
// Above, returned value of doctorize function is passed to yell function
- Default values:
function yell(name = "Silly Goose") {
return `HEY ${name.toUpperCase()}`;
}
yell("Soumya"); // HEY SOUMYA
yell(); // HEY SILLY GOOSE
// Above, if we don't pass any argument to yell function, then it takes the default value in function definition,
// here Silly Goose, else it takes whatever we pass as argument.
- Important gotcha:
function calculateBill(billAmount, taxRate = 0.13, tipRate = 0.15) {
console.log("Running Calculate Bill!!");
const total = billAmount + billAmount * taxRate + billAmount * tipRate;
return total;
}
// Suppose above, we want to pass the tipRate but not the taxRate and want taxRate to be default,
// then the only thing we can do is:
calculateBill(100, undefined, 0.66); // here the taxRate will default to 0.13 as
// we have passed undefined to it and the tipRate will be 0.66 as passed
Different ways of declaring functions
-
Functions are First class citizens:
-
It means JavaScript functions are values in themselves. They can be stored in variables and passed into other functions, just like any other piece of data in JavaScript. (see 3rd example below)
-
With function keyword
Important: These are hoisted, meaning JavaScript ‘hoists’ or puts them at the top of the file. So if we try to run a function defined with function keyword before it is defined/ above its definition, there’s no error and the function is executed successfully.
function doctorize(firstName) {
return `Dr. ${firstName}`;
}
- Anonymous function - function with no name
These are used in callbacks and IIFE: immediately invoked function expressions.
function (firstName) {
return `Dr. ${firstName}`;
}
- Function Expression
Important: These are not hoisted, meaning JavaScript doesn’t put them at the top of the file. So if we try to run a function not defined with function keyword before it is defined/ above its definition, there’s an error and the function fails to execute.
const doctorize = function(firstName) {
return `Dr. ${firstName}`;
};
-
Arrow Functions
-
Concise, shorter syntax
-
Don’t have own scope in refer to ‘this’ keyword
-
Are anonymous functions
const inchToCM = inches => {
return inches * 2.54;
};
// Implicit return: const add = (a, b = 3) => a + b; const inchToCM = (inches) => inches * 2.54;
// In case of only 1 parameter, we can omit the () around it const inchToCM = inches => inches * 2.54;
- Implicitly returning an object:
const makeABaby = (first, last) => ({ name: `${first} ${last}`, age: 0 });
- IIFE: Immediately Invoked Function Expression
(function(age) {
return `You are cool and age ${age}`;
})(10);
// Parantheses run first in JavaScript, so we have wrapped the function in ().
// The function immediately runs.
// The argument passed here is 10 for parameter age.
-
Methods:
-
A function which lives inside an object.
-
For e.g
console.log('hey')
: herelog
is the function andconsole
is the object. -
2 Ways to define methods:
const wes = {
name: "Westopher Bos",
// Method!
sayHi: function() {
console.log(`Hey ${this.name}`);
return "Hey Wes";
},
// Arrow function
wisperHi: () => {
console.log("hii wesss im a mouse");
},
// Short hand Method
yellHi() {
console.log("HEY WESSSSS");
}
};
-
Callback functions:
-
Function that is passed to another function used for something that will happen when something is done.
HTML:
<body>
<button class="clickMe">
Click Me!
</button>
</body>
Javascript:
// Click Callback const button = document.querySelector('.clickMe');
function handleClick() { console.log('Great Clicking!!'); }
button.addEventListener('click', handleClick); // everytime we click the button, the handleClick function is run.
button.addEventListener('click', function() { console.log('Nice Job!!!'); }); // everytime we click the button, the function inside is run.
// Timer Callback setTimeout(() => { console.log('DONE! Time to eat!'); }, 1000); // it runs the console.log after each 1 sec or 1000 milliseconds
Debugging
There are 2 aspects to debugging:
-
Debugging Tools
-
Mindset to tackle errors/bugs etc.
Here we will learn about Debugging Tools
- Console Methods:
-
Most basic form of debugging
-
e.g.
-
console.log
- normal logging, -
console.info
- similar toconsole.log
, -
console.error
- used for throwing/ handling errors (changes look of logs in console + gives a stacktrace), -
console.warn
- similar toconsole.error
but used for warnings(only UI difference than previous) -
console.table
- useful to use when we have data in array of objects where the objects have same keys, it formats it in a nice table
// For this data, you get below output in console:
const people = [
{ name: "Wes", cool: true, country: "Canada" },
{ name: "Scott", cool: true, country: "Merica" },
{ name: "Snickers", cool: false, country: "Dog Country" }
];
people.forEach((person, index) => {
console.table(person.name);
});
console.count
- counts how many times, say, a function is run
function doctorize(name) {
console.count(`Running doctorize for ${name}`);
return `Dr. ${name}`;
}
// console :
> doctorize('wes')
Running doctorize for wes: 1
< Dr. wes
> doctorize('wes')
Running doctorize for wes: 2
< Dr. wes
> doctorize('snickers')
Running doctorize for snickers: 1
< Dr. wes
> doctorize('wes')
Running doctorize for wes: 3
< Dr. wes
useful when we want to check why a function is running more times like hover element method triggering too many times.
The counting is based on what string we pass to console.count
.
console.group
- Group logs in a collapsible group
function doALotOfStuff() {
console.group('Doing some stuff');
console.log('Hey Im one');
console.warn('watch out!');
console.error('hey');
console.groupEnd('Doing some stuff');
}
doALotOfStuff();
When we use console.groupCollapsed('Doing some stuff');
instead of console.group('Doing some stuff');
, then we get the collapsed look by default.
- Call Stack or Stack Trace: Tells us what function called what function called what function and so on…
Example:
function doctorize(name) {
// console.count(`running Doctorize for ${name}`);
return `Dr. ${name}`;
}
function greet(name) {
doesntExist(); // Cause an error
return `Hello ${name}`;
}
function go() {
const name = doctorize(greet('Wes'));
console.log(name);
}
In this above example, doesntExist
function doesn’t exist, which will cause an error, when we run the go
function:
go()
Error:
debugging.js:32 Uncaught ReferenceError: doesntExist is not defined
at greet (debugging.js:32)
at go (debugging.js:37)
at <anonymous>:1:1
The error says that this error occurred at line 32 in function greet
. greet
was called by go
at line 37. The anonymous 1:1
comes as we ran it from our console, else it would have shown the line no. from where we would have called the go
function in code.
- Grabbing Elements
If we select something using the Elements tab in dev tools, and then flip over to Console tab, then we run $0
, then we get returned that selected item.
$0
: the selected element
$1
: the last selected element
$2
: the second last selected element
and so on…
We also have $
and $$
in the console. We can’t use them in code.
They are shorthand selectors.
- They help us to select things based on selectors
e.g. $('p')
= document.querySelector('p')
: selects first element that matches
$$('p')
= document.querySelectorAll('p')
: selects all elements that match
- Breakpoints:
To pause JavaScript from running at a certain line of code, we write debugger;
. The pausing of JavaScript only works when the DevTools is open. It helps us to peer into JavaScript at that very moment.
It shows us the call stack, values of local variables at that time and other useful stuff.
There are 2 buttons:
play/pause: clicking this runs JS till the next time debugger;
is encountered in code.
step over next function call: runs the code line by line.
We can also set breakpoints from the browser by ourselves in the sources tab. This does the same thing as a debugger;
i.e. stops the JS from running at that point.
- Network Requests:
To see the network requests, go to the Network tab in Devtools.
- Break on Attribute:
We can select an element in Elements tab and right click on it to select break on > attribute modifications. It means, when somebody changes its attributes, then there will be a breakpoint.
- Other types of breakpoints:
In Sources tab, there are other type of breakpoints too like mouse click, keyboard events, XHR or fetch breakpoints(breakpoint when a XHR request is made) etc.