Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 13, 2022 06:13 pm GMT

Introduction to Modern JavaScript

JavaScript (JS) is a lightweight, interpreted, prototype-based, multi-paradigm, single-threaded, dynamic language, supporting object-oriented, imperative, and declarative programming styles.
JavaScript is used on web browsers for client-side but can be also used on the server-side.

Each browser runs a JavaScript engine, the most common is V8 engine. This tutorial code will be run and tested on the browser debugger console.

To get started download and install VS Code and NodeJS. Once installed you are ready to go.

Output

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

This tutorial will be printing to browser console window.

console.log(Hello, World!); //Prints Hello, World! to the debugger console

JS doesnt need semicolon at the end of code line they are optional

For strings they can be enclosed with single or double quotes

Variables

JavaScript uses the keywords var, let and const to declare variables.
An equal sign is used to assign values to variables.
Lower camelCase highly recommended for variable names and should have meaning: firstName, lastName, masterCard, interCity.

4 Ways to Declare a JavaScript Variable:

  • Using var
  • Using let
  • Using const
  • Using nothingA variable declared without a value will have the value undefined. E.g. let carName;

A JavaScript name must begin with:

  • A letter (A-Z or a-z)
  • A dollar sign ($)
  • Or an underscore (_)

JavaScript Let

The let keyword was introduced in ES6 (2015).
Variables defined with let cannot be Redeclared.
Variables defined with let must be Declared before use.
Variables defined with let have Block Scope.

JavaScript const

The const keyword was introduced in ES6 (2015).

  • Variables defined with const cannot be Redeclared.
  • Variables defined with const cannot be Reassigned.
  • Variables defined with const have Block Scope.

It does not define a constant value. It defines a constant reference to a value.
As a general rule, always declare a variable with const unless you know that the value will change.

Use const when you declare:

  • A new Array
  • A new Object
  • A new Function
  • A new RegExp

Data type

String, number, boolean, object, undefined
typeof keyword is used indicate the type of a variable

var  num = 23var hello = hellovar isLate = truevar empty = undefined;var dob = new Date(1973,8,28);var person = {};console.log(typeof num);// prints number to consoleconsole.log(typeof hello); // prints string to consoleconsole.log(typeof isLate); // prints boleean to consoleconsole.log(typeof dob); // prints object to consoleconsole.log(typeof person); // prints object to consoleconsole.log(typeof empty); // prints undefined to console

Strings

var brand = "Shekey";console.log(typeof brand); // prints stringconsole.log(brand.length); //  prints 6console.log(brand.toUpperCase()); // prints SHEKEYconsole.log(brand.substring(0,4)); // prints Shekvar a = "She";var b = "key";console.log(a + b); // prints Shekeyconsole.log(a +" "+ b); // prints She Keyconsole.log(`${a}${b}`);// backticks ` ` in use prints Shekeyconsole.log(`${a}  ${b}`);// backticks ` ` in use prints She  key

Type Conversion

JavaScript variables can be converted to a new variable and another data type:

  • By the use of a JavaScript function
  • Automatically by JavaScript itselfNumber() Returns a number, converted from its argumentparseFloat() Parses a string and returns a floating point numberparseInt() Parses a string and returns an integer

The global method String() can convert numbers to strings.
It can be used on any type of numbers, literals, variables, or expressions:
The Number method toString() does the same.

JavaScript Objects

JavaScript objects are written with curly braces {}.
Object properties are written as key:value pairs, separated by commas.
An object is a collection of properties
You can access object properties in two ways:
objectName.propertyName
or
objectName["propertyName"]

var person = {    firstname: "Martin",    age: 47,    isMale: true,    balance: 453.435,    dob: new Date(1973, 1, 28).toJSON(),    address: {        city: "Nairobi",        postCode: "00100"    }};console.log(person);console.log(person.firstname);console.log(person.age)console.log(person.balance);console.log(person.address);console.log(person.address.city);console.log(Object.values(person));console.log(Object.keys(person));console.log(JSON.stringify(person));

Boolean

// Boolean takes on a true of false valuevar isAdult = true;console.log(isAdult); // prints trueThe ! operator can be used to negate (i.e. flip) the value console.log(!isAdult); //prints falseconsole.log(!true); //print falseconsole.log(!false) // prints true

Arrays

JavaScript arrays are written with square brackets.
Array items are separated by commas.
Used for storing multiple values

// Arraysvar names = [    "Alex",     "Joe",     "Ann",     "Mike"];console.log(names); // prints [Alex, Joe, Ann, Mike]console.log(names[0]); // prints Alexconsole.log(names[1]); // prints Joeconsole.log(names[2]); // prints Annconsole.log(names[3]); // prints Mikeconsole.log(names.length); // prints length of arrar i.e. 4

Arithmetic Operators

// Arithmetic Operatorsvar addition = 2 + 2;var subtraction = 2- 2;var division = 10/2;var multiplication = 10*2;var remainder = 10%2;var exponentation = 3**4console.log(addition);console.log(subtraction);console.log(division);console.log(multiplication);console.log(remainder);console.log(exponentation);

Functions

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: { }
A collection of statements that perform a task or calculate a value
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.

// Functionsfunction addNumbers(){    var addition = 2 + 5;    console.log(addition);};  addNumbers();
A function may or may not have parameters// Functionsfunction addNumbers(number1, number2){    var addition = number1 + number2;    return addition;};var result1 = addNumbers(2,5);var result2 =  addNumbers(7,5);console.log(result1); // prints 7console.log(result2); // prints 12

Arrow Function

Arrow functions were introduced in ES6.
Arrow functions allow us to write shorter function syntax:

let myFunction = (a, b) => a * b;
hello = () => {  return "Hello World!";}

or

hello = () => "Hello World!";

Loops

Used to repeat a piece of code over and over until a condition is met

// Loopsfor (var i=0; i<=10; i++){    console.log(i);}

Looping an array

// Loopsvar names = [    "Alex",    "John",    "Mary",    "Joe"];for (var i=0; i<names.length; i++){    console.log(names[i]);}

for of and foreach

// Loopsvar names = [    "Alex",    "John",    "Mary",    "Joe"];
// for offor (const name of names) {    console.log(name);}
// for eachnames.forEach(function(name) {    console.log(name);});

while loop

Repeats code until a certain condition is false

// While Loopsvar names = ["Alex","John","Mary","Joe","Bob"];var index = 0;while(index<names.length){    console.log(names[index]);    index+=1;}

do while loop

Loops at least once no matter the condition

do {    } while(true);

The break and continue keywords can be used within loops to terminate or go back to start of loop respectively.

Increment and Decrement operators (++ and --)

Num++ // Increments but returns the number before the increment

Example

// Postfixvar number = 0;console.log(number++); // prints 0console.log(number); // prints 1// Prefix increments/decrements  and returns the numberVar numberTwo  = 0;console.log(++numberTwo); // Prints 1

Comparison Operators

Evaluates values(numbers, strings, objects) and returns true or false
< ,!=, <= , >, >=, ==

Logical Operators

&&, ||, !

if statements

Allows execution of code based on a conditions
if( ){ }
if ( ) { } else{ }
if ( ) { } else if ( ) { } else { }
You can have as much else if ( ) { }

Ternary Statement ? :

var number = 6;var result = number % 2 ==0 ?"Even":"Odd";console.log(result)

switch statement

var gender = M;switch(gender){case M:break;case F:break;default:}

Hoisting

Hoisting is JavaScript's default behaviour of moving all declarations to the top of the current scope (to the top of the current script or the current function).
Accessing a variable outside its scope.
Use let or const key words to declare variables to avoid hoisting. Avoid var keyword.
const prevents the variable from being reassigned

JavaScript Classes

Use the keyword class to create a class.
Always add a method named constructor():

class ClassName {  constructor() { ... }}

A JavaScript class is not an object.
It is a template for JavaScript objects.
The constructor method is a special method:

  • It has to have the exact name "constructor"
  • It is executed automatically when a new object is created
  • It is used to initialize object properties
  • If you do not define a constructor method, JavaScript will add an empty constructor method.Use the keyword class to create a class.Always add a constructor() method.Then add any number of methods.
let myCar1 = new Car("Ford", 2014);let myCar2 = new Car("Audi", 2019);
class Car {  constructor(name, year) {    this.name = name;    this.year = year;  }}class Car {  constructor(name, year) {    this.name = name;    this.year = year;  }  age() {    let date = new Date();    return date.getFullYear() - this.year;  }}let myCar = new Car("Ford", 2014);

JSON

JSON is a format for storing and transporting data.
JSON is often used when data is sent from a server to a web page.

What is JSON?

  • JSON stands for Java*Script **Object **N*otation
  • JSON is a lightweight data interchange format
  • JSON is language independent *
  • JSON is "self-describing" and easy to understand

  • The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only. Code for reading and generating JSON data can be written in any programming language.

JSON Syntax Rules

  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays

JSON Objects
JSON objects are written inside curly braces.
Just like in JavaScript, objects can contain multiple name/value pairs:

{"firstName":"John", "lastName":"Doe"}

JSON Arrays
JSON arrays are written inside square brackets.
Just like in JavaScript, an array can contain objects:

"employees":[  {"firstName":"John", "lastName":"Doe"},  {"firstName":"Anna", "lastName":"Smith"},  {"firstName":"Peter", "lastName":"Jones"}]

Sources:

  1. Amigoscode YouTube Channel
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript
  3. w3schools.com

Original Link: https://dev.to/mmk2020/introduction-to-modern-javascript-5a50

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To