This content originally appeared on DEV Community and was authored by MMK2020
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 doesn’t 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 nothing
A 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 = 23
var hello = “hello”
var isLate = “true”
var empty = undefined;
var dob = new Date(1973,8,28);
var person = {};
console.log(typeof num);// prints number to console
console.log(typeof hello); // prints string to console
console.log(typeof isLate); // prints boleean to console
console.log(typeof dob); // prints object to console
console.log(typeof person); // prints object to console
console.log(typeof empty); // prints undefined to console
Strings
var brand = "Shekey";
console.log(typeof brand); // prints string
console.log(brand.length); // prints 6
console.log(brand.toUpperCase()); // prints SHEKEY
console.log(brand.substring(0,4)); // prints Shek
var a = "She";
var b = "key";
console.log(a + b); // prints Shekey
console.log(a +" "+ b); // prints She Key
console.log(`${a}${b}`);// backticks ` ` in use prints Shekey
console.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 itself
Number()
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 value
var isAdult = true;
console.log(isAdult); // prints true
The ! operator can be used to negate (i.e. flip) the value
console.log(!isAdult); //prints false
console.log(!true); //print false
console.log(!false) // prints true
Arrays
JavaScript arrays are written with square brackets.
Array items are separated by commas.
Used for storing multiple values
// Arrays
var names = [
"Alex",
"Joe",
"Ann",
"Mike"
];
console.log(names); // prints [‘Alex’, ‘Joe’, ‘Ann’, ‘Mike’]
console.log(names[0]); // prints Alex
console.log(names[1]); // prints Joe
console.log(names[2]); // prints Ann
console.log(names[3]); // prints Mike
console.log(names.length); // prints length of arrar i.e. 4
Arithmetic Operators
// Arithmetic Operators
var addition = 2 + 2;
var subtraction = 2- 2;
var division = 10/2;
var multiplication = 10*2;
var remainder = 10%2;
var exponentation = 3**4
console.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.
// Functions
function addNumbers(){
var addition = 2 + 5;
console.log(addition);
};
addNumbers();
A function may or may not have parameters
// Functions
function addNumbers(number1, number2){
var addition = number1 + number2;
return addition;
};
var result1 = addNumbers(2,5);
var result2 = addNumbers(7,5);
console.log(result1); // prints 7
console.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
// Loops
for (var i=0; i<=10; i++){
console.log(i);
}
Looping an array
// Loops
var names = [
"Alex",
"John",
"Mary",
"Joe"
];
for (var i=0; i<names.length; i++){
console.log(names[i]);
}
for
of and foreach
// Loops
var names = [
"Alex",
"John",
"Mary",
"Joe"
];
// for of
for (const name of names) {
console.log(name);
}
// for each
names.forEach(function(name) {
console.log(name);
});
while
loop
Repeats code until a certain condition is false
// While Loops
var 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
// Postfix
var number = 0;
console.log(number++); // prints 0
console.log(number); // prints 1
// Prefix increments/decrements and returns the number
Var 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 aconstructor()
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:
- Amigoscode YouTube Channel
- https://developer.mozilla.org/en-US/docs/Web/JavaScript
- w3schools.com
This content originally appeared on DEV Community and was authored by MMK2020
MMK2020 | Sciencx (2022-02-13T18:13:56+00:00) Introduction to Modern JavaScript. Retrieved from https://www.scien.cx/2022/02/13/introduction-to-modern-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.