You are on page 1of 17

JAVASCRIPT Fundamentals

On Visual Studio Code


Install Live Server
JavaScript ES6 Code Snippets
autoclose tag
autorename tag

INTRODUCTION
JavaScript is a lightweight, interpreted programming language with object-oriented capabilities. The core
of the language has been embedded in the modern web browsers. It now runs inside of database engines,
web servers, game consoles, and refrigerators.

Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should be included in or
referenced by an HTML document for the code to be interpreted by the browser. It means that a web page
need not be a static HTML, but can include programs that interact with the user, control the browser, and
dynamically create HTML content. For example, you might use JavaScript to check if the user has entered
a valid e-mail address in a form field.
JavaScript in Web Pages
JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page. If the "src" attribute is present, the <script> element must be empty.
For user agents that cannot or will not handle scripts, authors may include alternate content via
the NOSCRIPT element
Scripts without async , defer or type="module" attributes, as well as inline scripts, are fetched and
executed immediately, before the browser continues to parse the page.

Placing scripts in external files has some advantages:

 It separates HTML and code


 It makes HTML and JavaScript easier to read and maintain
 Cached JavaScript files can speed up page loads

<!DOCTYPE html>
<html>
<head>
<script >
document.write ("Hello World!");
</script>
<body>
</body>
</html>
Execution of JavaScript Programs

Javascript statements between <script></script> tags are executed in the order of appearance. The
execution of scripts occurs as part of web browser’s HTML parsing process. Your scripts should not
attempt to manipulate objects that have not been created.

Document Object Model (DOM)


Tree of nodes/elements created by the browser
JavaScript can be used to read/write/manipulate the DOM
Object Oriented representation

In the window there is document object the core of the DOM and the html element which is the html tag
and then the children.

5
console.dir(document);
console.log(document.domain);
console.log(document.url);
console.log(document.title);

How do engines work?


1. The engine (embedded if it’s a browser) reads (“parses”) the script.
2. Then it converts (“compiles”) the script to the machine language.
3. And then the machine code runs, pretty fast.
The engine applies optimizations at each step of the process. It even watches the compiled script as it
runs, analyzes the data that flows through it, and applies optimizations to the machine code based on that
knowledge. When it’s done, scripts run quite fast.

Comments in JavaScript
//
/* */

HTML (<!--This is a comment. Comments are not displayed in the browser-->)

Whitespace and Line Breaks


JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can use spaces,
tabs, and newlines freely in your program and you are free to format and indent your programs in a neat
and consistent way that makes the code easy to read and understand.

Semicolons are Optional Simple statements in JavaScript are generally.


Three Ways to Insert CSS

<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>

JavaScript is a case-sensitive language

DataTypes

The type of values that can be represented and manipulated in a programming language are known as
data types. The three primitive data types JavaScript supports are :
 Numbers, e.g., 123, 120.50 etc.
 Strings of text, e.g. "This text string" etc.
 Boolean, e.g. true or false
Note: Java does not make a distinction between integer values and floating-point values. All numbers in
JavaScript are represented as floating-point values. JavaScript represents numbers using the 64-bit
floating-point format defined by the IEEE 754 standard.

Trivial data types : null and Undefined each of which define a single value
Composite data type : object
This is a collection of values
array

Variables
Variables in JavaScript are containers which hold reusable data. Before you use a variable in a JavaScript
program, you must declare it. Variables are declared with the var keyword as follows.
var or let
Storing a value in a variable is called variable initialization. You can do variable initialization at the time of
variable creation or at a later point in time when you need that variable.

JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type.
Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of
value the variable will hold. The value type of a variable can change during the execution of a program
and JavaScript takes care of it automatically.

Variable names should not start with numeral (0-9). They must begin with a letter or an underscore
character. For example, 123test is an invalid variable name but _123test is a valid one. Should not use
any of the JavaScript reserved words.

Undefined and null


var abc;

console.log(typeof abc) --- Undefined …is a datatype


if you want to wipe out a variable use null
var abc = null;
console.log(typeof abc) - object

console.log(undefined == null) - true


console.log(undefined === null)  false

NaN – (not a number)

JavaScript evaluates expressions from left to right.

JavaSricpt Variable Scope


The scope of a variable is the region of your program in which it is defined. JavaScript variables have only
two scopes.
 Global Variables: A global variable has global scope which means it can be defined anywhere in your
JavaScript code.
 Local Variables: A local variable will be visible only within a function where it is defined. Function
parameters are always local to that function

Hoisting and 2 pass compilation in JavaScript

Hoisting is JavaScript's default behavior of moving declarations to the top.

In JavaScript, a variable can be declared after it has been used.

x = 5; // Assign 5 to x

elem = document.getElementById("demo"); // Find an element 


elem.innerHTML = x;                     // Display x in the element

var x; // Declare x

JavaScript Declarations are Hoisted

In ES2015, two other ways to declare variables were introduced. They are let and const

In JavaScript, a variable can be declared after it has been used.

In other words; a variable can be used before it has been declared.


Variable type let shares a lot of similarities with var but unlike var has scope constraints.
Unlike var, variables cannot be re-declared using let, trying to do that will throw a Syntax error: Identifier
has already been declared.

const is declared like var and let.Use const when you are sure a variable will not be redeclared.

Note: A variable declared with **const** MUST be initialized.

In JavaScript, there are 3 types of quotes.

1. Double quotes: "Hello".
2. Single quotes: 'Hello'.
3. Backticks: `Hello`.
Double and single quotes are “simple” quotes. There’s no difference between them in JavaScript.
Backticks are “extended functionality” quotes. They allow us to embed variables and expressions into a
string by wrapping them in ${…}, for example:
let name = "John";

// embed a variable
alert( `Hello, ${name}!` ); // Hello, John!
// embed an expression
alert( `the result is ${1 + 2}` ); // the result is 3

JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML.


 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().

CONTROL STATEMENTS

In JavaScript we have the following conditional statements:

Use if to specify a block of code to be executed, if a specified condition is true

Use else to specify a block of code to be executed, if the same condition is false

Use else if to specify a new condition to test, if the first condition is false

Use switch to specify many alternative blocks of code to be executed

The For Loop

The for loop has the following syntax:


for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

The While Loop

The while loop loops through a block of code as long as a specified condition is true.

Syntax
while (condition) {
  // code block to be executed
}

The switch statement is used to perform different actions based on different conditions.

The JavaScript Switch Statement

Use the switch statement to select one of many code blocks to be executed.

Syntax
switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

The Break Statement

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump
out" of a switch() statement.

The break statement can also be used to jump out of a loop.  

The break statement breaks the loop and continues executing the code after the loop (if any):

Example
for (i = 0; i < 10; i++) {
  if (i === 3) { break; }
  text += "The number is " + i + "<br>";
}

The Continue Statement

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop.

This example skips the value of 3:

Example
for (i = 0; i < 10; i++) {
  if (i === 3) { continue; }
  text += "The number is " + i + "<br>";
}
Operators

JavaScript supports the following type of operators

+ - * / % (Addition , Subtraction, Multiplication, Division, modulus


Unary
Bitwise
Boolean
Equality (datatype and value)
Relational

Logical Operators - && (Logical and) || (Logical or) !(Logical Not)

Objects

Objects are variables too. But objects can contain many values. JavaScript objects are containers
for named values called properties or methods.

var car = {type:"Fiat", model:"500", color:"white"};

Arrays

Arrays are collections

Reference Types and Examples


Built in objects

Date : It stores the date, time and provides methods for date/time management.
For instance, we can use it to store creation/modification times, to measure time, or just to print out the
current date.

Functions
Functions are the main “building blocks” of the program. They allow the code to be called many times
without repetition.
We’ve already seen examples of built-in functions, like alert(message), prompt(message,
default) and confirm(question). But we can create functions of our own as well.
function name(parameter1, parameter2, parameter3) {
  // code to be executed
}

Local Variables , Global Variables, Function parameters

Function parameters are listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.
A function can return a value back into the calling code as the result.
The simplest example would be a function that sums two values:
function checkAge(age) {
if (age > 18) {
return true;
} else {
return confirm('Do you have permission from your parents?');
}
}

let age = prompt('How old are you?', 18);

if ( checkAge(age) ) {
alert( 'Access granted' );
} else {
alert( 'Access denied' );
}

Function Invocation

The code inside the function will execute when "something" invokes (calls) the function:

 When an event occurs (when a user clicks a button)


 When it is invoked (called) from JavaScript code
 Automatically (self invoked)

A function with an empty return or without it returns undefined


If a function does not return a value, it is the same as if it returns undefined:

function doNothing() { /* empty */ }

alert( doNothing() === undefined ); // true

An empty return is also the same as return undefined:

function doNothing() {
return;
}

alert( doNothing() === undefined ); // true

What methods can we use to manipulate the DOM?

Methods to find an element or elements in your webpage:

 document.getElementById(id)
 document.getElementsByClassName(className)
 document.getElementsByTagName(tagName)
 document.querySelector(cssSelector)
 document.querySelectorAll(cssSelector)
 var salsMotto = document.getElementById("salsMotto");
 salsMotto.innerHTML = "Math is cool";
 The methods getElementsByClassName and getElementsByTagName return an HTMLCollection
object that acts like an array. That collection is "live", which means the collection is updated if
additional elements with tag name or class name are added to the document.

 var teamMembers = document.getElementsByClassName("team-member");


 for (var i = 0; i < teamMembers.length; i++) {
 console.log(teamMembers[i].innerHTML);
 }
 The method querySelectorAll() returns a NodeList, which also acts like an array. That list is "static",
which means that the list won't update even if new matching elements are added to the page. Most
likely, you won't run into the difference between the two return data types when you're using these
methods, but it's good to keep in mind.

 var teamMembers = document.querySelectorAll(".team-member");


 for (var i = 0; i < teamMembers.length; i++) {
 console.log(teamMembers[i].innerHTML);
 }

You might also like