A Simple Intro to Javascript

A Simple Intro to Javascript

In today's post, I'll share with you a simple introduction to Javascript language. It's not as complicated as it seems. The first thing to understand is the separation between the Javascript language, also called Vanilla Javascript and the Web API, which we interact with using Javascript.

Today I'll focus on the Javascript language, to learn more about the usage with Web API, browser interactions and the Nodejs environment I'm writing on it. This post aims to give you a first taste of what javascript is trying to not focus on its specific uses on a browser.

Requirements

This post will assume you have the basics of Programmation ( variables, functions, conditions, loops ). This post will not cover the ES6 part ( Ecmascript2015+ ), which implements more features to Javascript.

Types

There are multiple types that can be represented in javascript. You can check what type is a variable using the keyword typeof followed by the variable you want to check on. Example : typeof name; // string The basics one ( and those that you will be working most of the time with ) are :

Number

Unlike some other languages, Javascript group interger and float into Number type.

var age = 23;
var pi = 3.1415;

console.log(typeof age); // "number"
console.log(typeof pi); // "number"

String

String is like some languages, assigned using quote ' or double quote ".

var name = "John";
var country = 'US';

console.log(typeof name); // "string"
console.log(typeof country); // "string"

There is another way implemented by ES6 which is backquote. It allows you to use variables and values in your string.

Boolean

Boolean is like every languages either true or false. They are binary value used to validate a condition or not.

var isTrue = true;
var isFalse = false;

console.log(typeof isTrue); // "boolean"
console.log(typeof isFalse); // "boolean"

Array

Array in javascript is highly permissive. You can use it to store multiple types of value but it can be accessed like many languages.

var tab = [true, 32, "John"];
var tab_of_names = ["John", "Michael", "Foo", "Bar"];

console.log(typeof tab); // "array"
console.log(tab[1]); // 32
console.log(tab_of_names[2]); // "Foo"

Object

Objects in javascript is a grouping of values ( called property ) and functions ( called methods ). Unlike other languages, objects are not ( by default ) instantiated using classes. This feature was implemented by ES6.

var user = {
    name: "John",
    sayHello: function() {
        console.log('Hello');
    }
};

Objects are assigned using curly braces { }. It uses key-value pairs, first, you set the property name and then the property value separated by colon :.

You can create a generic object to create an instance of it using a function.

function user(name, age) {
    this.name = name;
    this.age = age;
}

var john = new User("John", 13);

The new keyword is used to instantiate objects.

Note: remember, Javascript is a programming language that is first-class function. That means functions are treated as variables which means you can pass a function as a variable to a function or assign a function to a variable. See an example below

First-class Function meaning

function sayHello() {
    console.log('Hello World!');
}

sayHello(); // "Hello World!"

var sayHelloWorld = sayHello; // Don't put parenthesis. If you put parenthesis the function is first executed and then the result is stored in the variables. See the image below

01.png

02.png

Null and Undefined

Null and undefined have the same purpose with a subtle difference. The first thing to know is that they both share the same conditional value as false. They will reject a condition. Undefined means that no value is assigned to the variable. On the other hand, null doesn't really mean that there is nothing assigned to the variable but says that the value is empty. ( I hope you're not lost xD ).

Here a visual difference

var u = undefined;
var u2;
var n = null;

console.log(typeof u); // undefined
console.log(typeof u2); // undefined
console.log(typeof n); // "object"

As you can see by default when you declare a variable, the variable is undefined. But null is actually an object. If it's too confusing, keep in mind that both are the same as false. If you put an undefined or null variable into a condition, it will not validate the condition.

Syntax

Now we will focus on the syntax, we will go fast on this part because javascript share the same syntax as most of the languages.

Comments

To use comments use // for single line comment or /* */ for multi lines comment.

// This is a single line comment

/* this is 
a 
multi
lines 
comment */

Variables

This post aims to introduce you to vanilla Javascript. To declare a variable we use var keyword, as you can see from the beginning of this post. But you should know that this keyword is now replaced by two keywords from ES6, let and const, which should be preferred over var keyword.

var name = "John";
var age;

If else

Here the javascript is basic, is and else statement. Javascript contains also an else if statement.

var isTrue = true;

if(isTrue) {
    console.log('it is true');
} 

if(isTrue) {
    console.log('it is true');
} else if(!isTrue) {
    console.log('it is false');
} else {
    console.log('it contains another value');
}

Note: As you can see here if you put a variable in condition by default it will check for a true value, or if a value exists. If the value is either null, undefined, false. The ! in the second condition means the condition will check for a false or unexisting value. See below for an explanatory image

03.png

For

For loops is also as basic as most languages. Though some features on For loop as added with ES6.

for(INITIALISATION ; CONDITION ; INCREMENT / DECREMENT) {
 //do something
}

for(var i = 0; i < 3; i++) {
    // Do something
}

Here i++ means the same as i = i + 1, you won't see a difference in a for loop using this but in other cases keep in mind that ++ can be put either before (++i ) or after ( i++ ). The difference then will be the value returned at the moment of incrementation.

var i = 1;
var a = i++; // a == 1 and i == 2

var j = 3;
var b = ++j; // b == 4 and j == 4

In the second case, j was incremented before b was assigned.

While and Do While

The syntax for while and do-while is also the simplest.

while(CONDITION) {
    Do something
}

while(isTrue) {
    // Do something
}

do {

} while(isTrue);

Logical and Comparison Operators

There is multiple logical operator use for conditions.

== and ===

Compare if the values are equals then return true else false. The difference between the two is that === compare type as well.

true == true // true
true == "true" // true

true === true // true
true === "true" // false

!= and !==

Compare if both values are different return true, return false otherwise.

true != false // true
3 != "3" // false

true !== true // false
true !== "true" // true

< , > , <= , >=

Those compare numbers. The difference between <, > and <=, >= is that in the two first operators it strictly compare.

2 > 3 // false
4 < 5 // true
4 < 4 // false

4 <= 4 // true
5 >= 9 // false
10 >= 10 // true

&&, ||

As we already discussed above,! means the opposite of the value tested. !true equals false. We will discuss the two other now. && means AND operators and || means OR operator.

(CONDITION1) && (CONDITIONS2) // Both condition should be true in order to pass this test

(3 === 3) && true // true
(3 > 5) && true // false

(CONDITION1) || (CONDITIONS2) // One of both should be true in order to pass this test

true || true // true
false || true // true
false || false // false

Note: Keep in mind that when using && if the first condition is false then the check is stopped and the second condition is not checked. This is important if your second check contains a modification to a variable

Functions

Javascript provides a simple keyword to define a function which is function keyword ( yes sometimes don't search for difficulty xD ).

function name1() {
    // Do something
}


function name_of_function(param1, param2) {
    // Do something
}

name_of_function(value1, value2);

Don't forget that function is assignable to variable and can be used as a parameter for other function. We will see an example in the next section

Closures

Closures in Javascript are function that returns function in order to customize the returned function with dynamic variables. Why there are useful? Here is a simple example but in a real project, it is used for more complex operations. For example, you can see a usage of closures with React and Redux.

function arithmetic_operation(op) {
    if(op == '+') {
        return function(a, b) {
            return a + b;
        }
    }
}

// Here you can define a function called add using the arithmetic_operation

var add = arithmetic_operation('+');

console.log(add(2, 4)); // 6

Here is another example but keeping a dynamic value for creating your function

function greeting(lang) {
    return function(name) {
        console.log('Hello my name is ' + name + ' my lang is ' + lang);
    }
}

var fromEnglish = greeting('English');
var fromSpain = greeting('Spanish');

var name = "John";

console.log(fromEnglish(name)); // 'Hello my name is john my lang is English'
console.log(fromSpain(name)); // 'Hello my name is John my lang is Spanish'

04.png

Regular Expression ( regex )

You can make use of regular expression ( regex ) to filter a string from a specific pattern. We will not dive deep into regex here but if you want to know more I'll write a post soon about it. There is two way of using regex. First is by entering the pattern with / /. The second way of doing it is by using the Regex object from Javascript.

var reg1 = /[a-z]/; // Will match every lowercase character

var reg2 = new Regex('a-z');
var reg3 = new Regex('/[a-z]/');

use /[a-z]/ or new Regex(); You can then test if the regex pattern matches a string. The result will be true if the pattern matches the string or false otherwise.

var str = "This is a blog post";

reg1.test(str); // true
reg2.test(str); // true

You can also use the match method which will return the matched pattern of a string.

str.match(reg1); // h

We will dive deeper in a future post about Regex as this post mostly intend to take a first step into Javascript.

Conclusion

I hope you have a simple understanding of Javascript language and its syntax. Javascript is not as complicated as it sounds, focus on learning the syntax and how first-class function features works. If something wasn't clear enough please tell me in the comment. Make sure to check other posts like the basics of programming which is complementary to this one.

#javascript#js#beginners
 
Share this