Javascript is a text-based programming language used to make web pages interactive. Combining javascript, Html, and CSS you can transform a static page into an interactive page. in short, javascript adds behavior to web pages.
Javascript is not only used on the client-side (The browser), it can also be used on the server-side to retrieve and store data on a database, manipulate and download files. etc.
Overview
In this article, we will cover:
Adding Comments into our code
Variable and how to declare them.
Operators
Basic Datatypes
Functions
Objects
Arrays
Pre-requisite
Basic coding skills, knowing how to use a code editor, and willingness to learn
So let's get started.
What are comments
Comments are lines of code that are usually ignored by javascript. they are basically used to add notes to yourself and to programmers who might want to know what your code is about.
There are two ways you would add comments to your code:
- Single-line comment, which is usually used as an inline comment
// This is a single-line comment.
- Multi-line comment
/* This is a
multi-line comment */
What are variables
Variable are just containers for storing data or data values. All JavaScript variables must be identified with unique names, which are called identifiers.
Identifiers can be short names like x and y or more descriptive names age, sum, etc.
To learn more about the rules of naming variables in javascript, visit MathBits.
let's continue.
There are 3 kinds of declaration in javascript, namely:
- Var
We declare variables by putting the var keyword in front of the identifier, and to store the value to a variable, we use the = operator before the value, like so.
// declaring a variable
var name;
// Storing a value to the variable name
name = "stephen";
- The let
let is a block or local scope, introduced in the newer version of javascript (ES6).
When we say let is a block scope we mean that it cannot be accessed outside the scope. Let us explain it in code.
We will start explaining using the var keyword for a good understanding. let's say we declare a variable using the var keyword which is a global or function scope.
var name; // the variable is accessed within the function
function functionScope(){
name = "stephen";
}
functionScope();
console.log(name);
// Output: stephen
Back to the let keyword, let's recall what we mean by block scope, when we say something is blocked scope, we mean that it cannot be accessed outside the block scope. In javascript, a block is delimited by a pair of curl braces '{}'.
using the above example, let's look at an example of block scope.
function functionScope(){
{
let blockScope = "this is a block scope" // it cannot be accessed outside this scope.
}
}
functionScope();
console.log(blockScope); // Uncaught ReferenceError: blockScope is not defined
The Const
Unlike var and let, const you can't declare the identifier, then store its value later. it will show the following error.
Uncaught SyntaxError: Missing initializer in const declaration
//
const name;
name = "stephen"
// output: Uncaught SyntaxError: Missing initializer in const declaration
// the right way
const name = "stephen"
console.log(name)
// output: stephen
N/B To learn the difference between the var, let, and const, head on to GeeksforGeeks they have a great article on that.
Operators
Operators in javascript perform some operation on single or multiple operands and produce a result.
Javascript has the following categories of operators:
Arithmetic operators
The basic arithmetic operators includes +, -, %, / and *.
Example in code:
var x = 10;
var y = 5;
var z = x + y; // console.log(z) 15
z = x- y // 5
z = x % 2 // 1 returns the remainder
z = x*y // 50
z = x/y // 2
- Conditional operators
In javascript, we use a conditional statement to perform different actions for different decisions and we can achieve this either by using the if-else statement or the switch statement.
The if else-statement
Syntax
if (condition is true) {
statement is executed
}
else if() {
statement is executed
}
else{
statement is executed
}
- Use if to specify a block of code to be executed, if a specified condition is true Use else if to specify a new condition to test, if the first condition is false
- Use else to specify a block of code to be executed if both the 1st and the 2nd condition is false
Example
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
The Switch statement
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Explanation
- The switch expression is evaluated once.
- The value of the expression is compared with the values of each case.
- If there is a match, the associated block of code is executed.
- If there is no match, the default code block is executed.
Example
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
- Comparison Operators
This compares two operands and returns a boolean value, a true or a false.
Example
var a = 10;
var b = '11';
var c = 3;
a == b; // returns true "Compares the equality of two operands without considering type."
a === b; // returns false "Compares equality of two operands with type."
a == c; // returns true
a != b; // returns true "Compares inequality of two operands."
c > a; /* returns false "Returns a boolean value true if the left-side value is greater than the right-side value; otherwise, returns false.
"*/
c < a; /* returns true "Returns a boolean value true if the left-side value is less than the right-side value; otherwise, returns false.
" */
a >= c; /* returns false "Returns a boolean value true if the left-side value is greater than or equal to the right-side value; otherwise, returns false.
" */
a <= b; /* returns false "Returns a boolean value true if the left-side value is less than or equal to the right-side value; otherwise, returns false.
" */
- Logical operator
logical operators are used to combining two or more conditions. these are the And operator (&&), the Or operator(||), and the Not operator(!)
Example
var a = 5, var b = 10;
(a != b) && (a < b); // returns true
(a > b) || (a == b); // returns false
(a < b) || (a == b); // returns true-
!(a < b); // returns false
!(a > b); // returns true
- Assignment operator
We have been using this operator from all our examples. This is basically used to assign values to variables (=)
- Ternary operator
The ternary operator is short for the if-else statement
Syntax
<condition> ? <value1> : <value2>;
Example in code
var a = 10, b = 5;
var c = a > b? a : b; // value of c would be 10
var d = a > b? b : a; // value of d would be 5
Basic Data types
Variable in javascript is not directly associated with any particular value type, this means that a variable can be assigned and reassigned values of all types, Example.
let num = 42; // num is now a number
num = 'bar'; // num is now a string
num = true; // num is now a boolean
Basic data types in javascript include:
- Boolean type
boolean only contain two values true and false
var x = true;
if(x){
// code is executed
}
x =false
if (x){
// code will not execute
}
- String
the string is a series of characters. it's written with quotes, Example
let name = "string"
console.log(name) /// string
- Number
Numbers can be written with or without the decimal, for example.
let number = 4;
let number = 4.0;
- undefined
If you declare a variable without a value, this will return undefined. for example.
let name;
console.log(name) // output: undefined
Null type
null is the intentional absence of variable value. You can assign null to a variable to denote that currently, that variable does not have any value but it will have later on. Example
let myValentine = Null;
console.log(myValentine) // Null
Functions
the function is a set of statements or a block of code that is designed to perform a particular task.
To define a function, we use the function keyword followed by a unique function name, followed by a parenthesis and two curly braces.
Syntax
function functionName() {
// code
}
For a function to work, it should take some input and return an output where there is some obvious relationship between the input and the output *Source.
function square(number) {
return number * number;
}
- Calling a function
To call a function later somewhere in your code, you need to write the name of the function followed by parenthesis outside the function block, like the following.
function square(number) {
return number * number;
}
square() // calling or invoking the function.
To read more about function, visit Mdn
Objects
Objects are the most important data types and form the building blocks for javascript. objects are a collection of properties, which property is an association between a name (or key) and a value.
Let's look at an example of a javascript object.
let car = {
make : "Toyota",
doors : 4,
established : "2000"
}
Objects properties can be accessed in two ways:
- using Dot notation
- using brackets notation
Syntax
objectName.propertyName
- using Dot notation
let car = {
make : "Toyota",
doors : 4,
established : "2000"
}
// accessing door
console.log(car.doors) // 4
- Using brackets notation
let car = {
make : "Toyota",
doors : 4,
established : "2000"
}
// accessing door using brackets notation
console.log(car.[doors]) // 4
You can also add and manipulate properties in objects.
Example
let car = {
make : "Toyota",
doors : 4,
established : "2000"
}
// adding property using dot notation
car.color = "red"
let car = {
make : "Toyota",
doors : 4,
established : "2000"
}
// adding property using brackets notation
car[color] = "red"
- Manipulating properties in objects
let car = {
make : "Toyota",
doors : 4,
established : "2000",
car.color = "red"
}
// updating property using dot notation
car.color = "green"
// using brackets notation
car[color] = "green"
The topic for objects is broad, to read more visit GeeksForGeeks
Arrays
In javascript, the array is a single variable that is used to store different elements. you can access an array in two ways
Syntax
let array = [] // one way to declare a variable
let array = new array() // second way
- Accessing array elements
We can access the data inside an array using indexes, like the following.
const array = [50, 60, 70];
const data = array[1];
console.log(data) // 60
- modifying array elements
You can modify elements in an array using indexes like the above example.
const array = [50, 60, 70];
array[0] = 30;
console.log(array) // [30,60,70]
You can manipulate data in an array with push, pop, shift and unshift.
manipulating with push
you can append data to the end of the array with push, for example.
const arr1 = [1, 2, 3];
arr1.push(4);
console.log(arr1) // [1,2,3,4]
manipulating with pop
pop method removes the last element from an array and returns that element.
const threeNums = [1, 4, 6];
const removed = threeArr.pop();
console.log(removed); // 6
console.log(threeNums); // [1,4]
manipulating with shift
shift method removes the first element in an array. for example.
const threeNums = [1, 4, 6];
const removed = threeArr.shift();
console.log(removed); // 1
console.log(threeNums); //[4,6]
manipulating arrays with unshift
Unshift methods add elements at the beginning of an element.
const threeNums = [1, 4, 6];
threeArr.unshift("valentine");
console.log(threeNums); //["valentine", 4,6]
Conclusion
We have come to the end of the articles, I hope you have learned the basics of javascript. to learn more on javascript Mdn
let's connect Twitter