0% found this document useful (0 votes)
18K views32 pages

Beginner Javascript: Browser (Chrome) Shortcuts

The document provides an overview of beginner JavaScript concepts including: - Running JavaScript in browsers via the console, script tags, and external files. - Variables, data types, and variable scoping rules. The main data types covered are strings, numbers, objects, booleans, undefined, and null. - String methods like concatenation and interpolation. - Best practices for naming variables and code quality tools. - Notes that the overview is a work in progress and covers material from a beginner JavaScript course.

Uploaded by

Rakesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18K views32 pages

Beginner Javascript: Browser (Chrome) Shortcuts

The document provides an overview of beginner JavaScript concepts including: - Running JavaScript in browsers via the console, script tags, and external files. - Variables, data types, and variable scoping rules. The main data types covered are strings, numbers, objects, booleans, undefined, and null. - String methods like concatenation and interpolation. - Best practices for naming variables and code quality tools. - Notes that the overview is a work in progress and covers material from a beginner JavaScript course.

Uploaded by

Rakesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

8/29/2020 Beginner JavaScript

Beginner JavaScript
Last Edited Aug 29, 2020 3:23 AM

Tags Development JavaScript

Github Repo https://github.com/geekysrm/javascript-notes

Add a comment…

Notes In Progress. Notes are from Wes Bos' course:


BeginnerJavaScript.com

This notes is being made and kept up to date by geekysrm


(https://soumya.dev).
[geekysrm on Twitter, GitHub and elsewhere].

If this helped you, please buy me a coffee.

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.

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 1/32
8/29/2020 Beginner JavaScript

• Also we can run it in a script tag:

<script> console.log('Heyyy'); </script>


HTML

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 with src attribute:

<script src='relative path to js file'></script>


JavaScript

• 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 and const were introduced in ES6 (newer).

• var and let can be updated but not const .

var x = 'hey'; y = 'hi'; let cool = true; cool = false; const age = 10;
age = 11; // wrong: throws error
JavaScript

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 2/32
8/29/2020 Beginner JavaScript

• 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
JavaScript

• 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 use let . Almost never use var .

• 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.


NOT DONE THIS - DO LATER

Types
SNOBUS'N
1. String
2. Number

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 3/32
8/29/2020 Beginner JavaScript

3. Object

4. Boolean
5. Undefined
6. Symbol : Always gives a guaranteed unique identifier
7. Null
Everything except Object is Primitive type, Object is special one.

String
• used for holding text

• 3 ways to create strings:


1. using single quotes:

const first = 'Soumya';

2. using double quotes:


const middle = "Ranjan";

3. using backticks:

const last = `Mohanty`;


JavaScript

• 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"
JavaScript

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 4/32
8/29/2020 Beginner JavaScript

• Multi-line string:
1.

const song = 'Oh \ I like \ pizza'; console.log(song); // Oh I like


pizza
JavaScript

2.

const song = `Oh I like pizza`; console.log(song); /* Oh I like pizza


*/
JavaScript

2nd one using backticks is mostly used.

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 5/32
8/29/2020 Beginner JavaScript

• 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


JavaScript

• 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.
JavaScript

• Backticks also used for tagged template literals.

• Backticks are helpful for creating HTML:

const html = ` <div> <h2>Hey everyone! I am ${name}.</h2> </div> `;


JavaScript

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
JavaScript

• typeof is used to find out the 'type' of a variable.

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 6/32
8/29/2020 Beginner JavaScript

• Various operations: addition, subtraction, multiplication, division can be done


with nos.

• Example

"10" * "10" // 100 (number) - converts the strings to number


JavaScript

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
JavaScript

• 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
JavaScript

• Example

0.1 + 0.2 // 0.30000000000000004


JavaScript

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

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 7/32
8/29/2020 Beginner JavaScript

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
JavaScript

• 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


JavaScript

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
JavaScript

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 8/32
8/29/2020 Beginner JavaScript

Booleans and Equality


• A boolean variable can be either true or false .

• Example:

const age = 18; const ofAge = age > 18; console.log(ofAge); // false
JavaScript

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 9/32
8/29/2020 Beginner JavaScript

• Equal signs:

• = sign: used for assignment/ updation of values

let name = 'Soumya'; name = 'Raja';


JavaScript

• Out of == and === , you should almost always use === .

• == and === are used for equality comparison.

console.log(age === 18); // true


JavaScript

• == 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
JavaScript

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
JavaScript

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.

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 10/32
8/29/2020 Beginner JavaScript

e.g:
• console.log('hey'); returns undefined , logs hey .

• 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>
JavaScript

• 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
JavaScript

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'); }
JavaScript

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 11/32
8/29/2020 Beginner JavaScript

• Calling a function:

// Function call or run calculateBill(); // running calculateBill


(returns undefined)
JavaScript

• 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
JavaScript

• 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
JavaScript

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 12/32
8/29/2020 Beginner JavaScript

• 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);


JavaScript

• So, we can either pass direct value or variables holding value or expressions
resulting in a value to a function as arguments.

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 13/32
8/29/2020 Beginner JavaScript

• 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
JavaScript

• 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.
JavaScript

• 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
JavaScript

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)

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 14/32
8/29/2020 Beginner JavaScript

• 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}`; }


JavaScript

• Anonymous function - function with no name

These are used in callbacks and IIFE: immediately invoked function expressions.

function (firstName) { return `Dr. ${firstName}`; }


JavaScript

• 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}`; };


JavaScript

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 15/32
8/29/2020 Beginner JavaScript

• 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;
JavaScript

• Implicitly returning an object:

const makeABaby = (first, last) => ({ name: `${first} ${last}`, age:


0 });
JavaScript

• 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.
JavaScript

• Methods:

• A function which lives inside an object.

• For e.g console.log('hey') : here log is the function and console 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'); } }
JavaScript

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 16/32
8/29/2020 Beginner JavaScript

• Callback functions:

• Function that is passed to another function used for something that will
happen when something is done.

<body> <button class="clickMe">Click Me!</button> </body>


HTML

// 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
JavaScript

Debugging
There are 2 aspects to debugging:
1. Debugging Tools
2. Mindset to tackle errors/bugs etc.

Here we will learn about Debugging Tools

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 17/32
8/29/2020 Beginner JavaScript

1. Console Methods:

• Most basic form of debugging

• e.g.

• console.log - normal logging,

• console.info - similar to console.log ,

• console.error - used for throwing/ handling errors (changes look of


logs in console + gives a stacktrace),

• console.warn - similar to console.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); });
JavaScript

• 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
JavaScript

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

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 18/32
8/29/2020 Beginner JavaScript

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();
JavaScript

When we use console.groupCollapsed('Doing some stuff'); instead of


console.group('Doing some stuff'); , then we get the collapsed look by
default.

2. 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); }
JavaScript

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
JavaScript

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

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 19/32
8/29/2020 Beginner JavaScript

console, else it would have shown the line no. from where we would have
called the go function in code.
3. 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
4. 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.
5. Network Requests:

To see the network requests, go to the Network tab in Devtools.


6. Break on Attribute:

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 20/32
8/29/2020 Beginner JavaScript

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.
7. 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.

Scope
Scope answers the question: "Where are my variables and functions available to
me?".

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 21/32
8/29/2020 Beginner JavaScript

• Global Variables
Available anywhere. They are created not inside a function, module, if statement
etc.
<script> const first = 'Soumya'; </script> //here first is a global
variable.

In the browser, the global scope is called window. Methods like setTimeout,
setInterval are available on the window object.

const first = 'wes'; let second = 'bos'; var third = 100;


console.log(window.first); // undefined console.log(window.second); //
undefined console.log(window.third); // 100
JavaScript

The above occurs because var variables are attached to the window object and
are globally scoped, whereas const and let variables are globally scoped but
not attached to the window object.

Anything except let and const declared things which are globally declared
are attached to window object.

function sayHi() { console.log('HI'); } sayHi(); // HI window.sayHi();


// HI
JavaScript

Using global scoped variables etc. are not advised in general.

More examples:

const age = 100; function go() { const cool = true; } go();


console.log(age); // 100 console.log(cool); // Uncaught ReferenceError:
cool is not defined
JavaScript

Above, cool is function-scoped. Function scoping means anything declared


inside of a function is only accessible inside the function and not outside (unless
we return it from the function and store the returned value in a variable when
the function is run)
Scope Lookup: If variables are not found inside a function, it goes a level higher

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 22/32
8/29/2020 Beginner JavaScript

to look for the variable in that scope and if its not available in that scope as well,
it goes another level higher.

const age = 100; function go() { const cool = true; console.log(age);


console.log(cool); } go(); // console output: // 100 - this is printed
as it doesn't find variable age in go function scope it goes a level
higher to find it // true
JavaScript

const age = 100; function go() { const cool = true; const age = 200; //
global variable age has been shadowed by this variable - shadow
variable console.log(age); console.log(cool); } go(); // console
output: // 200 - this is printed because it finds variable age in go
function scope only // true
JavaScript

Block Scope:

if(1 === 1){ const cool = true; // or let cool = true; }


console.log(cool); //Output: Uncaught ReferenceError: cool is not
defined
JavaScript

if(1 === 1){ var cool = true; } console.log(cool); //Output: true - var
varibales leak outside the block
JavaScript

A set of curly brackets are referred to as a block.

To access a variable outside a block, we use:

let cool; if(1 === 1){ cool = true; } console.log(cool); //Output: true
JavaScript

Above the cool variable is declared in the higher scope, here global scope.

var variables are function scoped. Let's see here:

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 23/32
8/29/2020 Beginner JavaScript

function isCool(name) { if (name === 'wes') { var cool = true; }


console.log(cool); return cool; } isCool('wes'); //Output: true
JavaScript

Above, as the variable cool was declared using var keyword, it was not
limited within the if block, rather it was available inside the entire isCool
function.
let and const variables are block scoped.

Example:

const dog = "snickers"; function logDog() { console.log(dog); }


function go() { const dog = "sunny"; logDog(); } go(); // Output:
snickers
JavaScript

Above happens as JavaScript uses Lexical Scoping or Static Scoping. It means,


variable lookup or scope lookup happens where the functions are defined not
where they are run.
In the above example, logDog function is defined above where there is no dog
variable inside its definition, so it goes and looks in upper/higher scope to find
value as 'snickers'. It doesn't care where it is run, in this case inside go function.

const dog = "snickers"; function logDog(dog) { console.log(dog); }


function go() { const dog = "sunny"; logDog("Rufus"); } go(); //Output
: Rufus
JavaScript

The above is the output because here the function logDog creates a local
variable for parameter dog which has value 'Rufus' passed to it. So, 'Rufus' is
printed.

Best practices for variables:

• Try not to create global variables.

Function Scoping:

Functions are scoped the exact same way as variables.

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 24/32
8/29/2020 Beginner JavaScript

function sayHi(name) { function yell() {


console.log(name.toUpperCase()); } } yell(); // Output: Uncaught
ReferenceError: yell is not defined
JavaScript

Just like variables, functions are scoped to the parent function. So yell function
above is only accessible inside sayHi function, and not outside it.

Hoisting
Allows us to access functions and variables before they are created.
2 things that are hoisted in JavaScript:

• Function declarations

• Variable declarations

Function hoisting

sayHi(); function sayHi() { console.log('Hi'); } // Output - Hi


JavaScript

The above happens because when we run the JavaScript file, JavaScript compiler will
take all function declarations and move them to the top of the file available for use.
Suggestion: Always define functions before using them.
Note: Functions made using a variable are not hoisted.

add(10,20); const add = function(a,b) { return a + b; } //Output - Uncaught


ReferenceError: Cannot access 'add' before initialization
JavaScript

Variable hoisting

console.log(age); var age = 10; // Output - undefined


JavaScript

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 25/32
8/29/2020 Beginner JavaScript

This happens because JavaScript hoists the variable declaration but not the actual
setting of the values or assignment. This essentially means this happens:

var age; console.log(age); age = 10; // Output - undefined


JavaScript

Closures
Ability to access a parent level scope from a child scope even after the parent
function has been closed/terminated.

function outer() { const outerVar = 'Hey I am the outer var!'; function


inner() { const innerVar = 'Hey I am an inner var!' console.log(innerVar)
console.log(outerVar) } return inner; } const innerFn = outer() innerFn()
// Output - // "Hey I am an inner var!" // "Hey I am the outer var!"
JavaScript

This happens because even though outer function is done running in the line
const innerFn = outer() , the variable outerVar is still maintained in
memory/accessible at a later time even if it is not returned. It is not cleaned up or
garbage collected.

More examples:

function createGreeting(greeting = '') { const myGreet =


greeting.toUpperCase() return function (name) { return myGreet + ' ' + name
} } const sayHello = createGreeting('hello') const sayHey=
createGreeting('hey') console.log(sayHello('wes'))
console.log(sayHello('kait')) console.log(sayHey('kait')) // Output - //
"HELLO wes" // "HELLO kait" // "HEY kait"
JavaScript

The myGreet variable is still accessible even after createGreeting is done running.

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 26/32
8/29/2020 Beginner JavaScript

function createGame(gameName) { let score = 0; return function win(){ score


+= 1; return `Your game ${gameName} score is ${score}` } } const hockeyGame
= createGame('hockey') const soccerGame = createGame('soccer') // In
console run, // hockeyGame() // "Your game hockey score is 1" //
hockeyGame() // "Your game hockey score is 2" // hockeyGame() // "Your game
hockey score is 3" // soccerGame() // "Your game soccer score is 1" //
soccerGame() // "Your game soccer score is 2"
JavaScript

score is a private variable here. We can access multiple games at once like that.

The DOM: Intro to the document


JavaScript is used in all kinds of places. The most popular way we get introduced to
JS is through web browser.
When we view HTML in the browser, the browser turns the HTML into the DOM:
Document Object Model. We can see the DOM in the Elements tab in Dev Tools.
We can interact with the DOM like listening for clicks, add/remove elements from
the DOM, fetch new data, play music and video etc. using JavaScript.
The window:

• Global scope of browser

• All global variables are stored.

• Helpful properties like location, innerWidth present on window object.

• It is everything about the currently open window including the browser bar,
tabs, scrollbars etc.
The document:

• Responsible for everything from <html> to </html>

• Not concerned with tabs, scrollbar, browser bar etc.


The navigator:

• Higher level than window.

• gives info about the browser and the device that it's on

• things like webcam, audio access, battery level, GPS and other device specific
features live on navigator.

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 27/32
8/29/2020 Beginner JavaScript

The DOM: Selecting elements on the page


Where to load JavaScript if we are selecting elements on the page?
Always load it before the closing body tag ( </body> ). It is because, we need to have
all elements before we start selecting them in JavaScript. We get null if we try to
grab elements placing the <script> tag in the head because the elements are not
yet created when the JavaScript is run.
Other option: (to use in <head> tag)

• use defer and async

• we can listen for the DOMContentLoaded event and then try to select elements
from the page.
Best way: Load the JS before the </body> tag.

• querySelector: Returns first match

const p = document.querySelector('p');
JavaScript

• querySelectorAll: Returns all matches as a NodeList (like array but without array
helper functions)

const p = document.querySelectorAll('p');
JavaScript

In querySelector and querySelectorAll, the argument we pass is nearly similar to


CSS Selectors.
We can use things like:

• .item (element with class of item) or div.item (div with class of item) etc.

• Parent-child selector: e.g. to grab images inside div with class item

const img = document.querySelector('.item img');

<div class="items"> <div class="item item1"> <img src="http://img1.com" >


</div> <div class="item"> <img src="http://img2.link" > </div> </div>
HTML

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 28/32
8/29/2020 Beginner JavaScript

In above HTML, suppose if we want just the first item and find the image inside of
the item.
We have 2 options:
1. document.querySelector('item img');
2. List

const item1 = document.querySelector('.item1'); const item1Img =


item1.querySelector(img); //important
JavaScript

Note: We also have dated/old ways of selecting elements from DOM like
getElementById , getElementsByClassName , getElementsByTagName etc.

The DOM: Element Properties and Methods


If we do console.dir after selecting an element then we can see that the selected
element is actually an object and we can see the object properties.

const h2 = document.querySelector('h2'); console.dir(h2); //Output - We get


many properties
JavaScript

We can use these properties as either getters or setters.


e.g Getter: console.log(h2.textContent); // I am an h2.
Setter: h2.textContent = 'new h2 content';

Difference between textContent and innerText:


Suppose we have the following HTML:

<h2> I am a heading. <style> h2 { color: red; } </style> </h2>


HTML

In JavaScript:

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 29/32
8/29/2020 Beginner JavaScript

const heading = document.querySelector('h2');


console.log(heading.textContent); // I am a heading. h2 {color: red; }
console.log(heading.innerText); // I am a heading.
JavaScript

Other example for above:


HTML:

<h2> I am a heading. <span> I am hidden! </span> </h2> // We hide the span


by display:none <style> h2 span { display: none; } </style>
HTML

JavaScript:

console.log(heading.textContent); // I am a heading. ↵ I am hidden!


console.log(heading.innerText); // I am a heading.
JavaScript

innerText is aware of CSS styling.

innerHTML:

console.log(heading.innerHTML); // I am a heading. ↵ <span>I am hidden!


</span>
JavaScript

outerHTML:

console.log(heading.outerHTML); // <h2> I am a heading. <span>I am hidden!


</span> <h2>
JavaScript

Example:

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 30/32
8/29/2020 Beginner JavaScript

To add pizza( ) at the end:

• List

pizzaList.textContent = `${pizzaList.textContent} 🍕`;


JavaScript

But the above method becomes slow for long text.

• Instead we can use insertAdjacentText :

pizzaList.insertAdjacentText('beforeend', 🍕)
JavaScript

Element vs node:

Element: wrapped inside tags


Node: can be anything

<p> //node //element "Hey" //node "there" //node </p> //node


//element
JavaScript

Element properties & methods: https://developer.mozilla.org/en-


US/docs/Web/API/Element

Node properties & methods: https://developer.mozilla.org/en-


US/docs/Web/API/Node

The DOM: Working with classes

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 31/32
8/29/2020 Beginner JavaScript

https://www.notion.so/Beginner-JavaScript-e2ef045754d14e96b93791f638bbcaf6 32/32

You might also like