Mari kenal Javascript

console.log(‘Hello World’);

// single js comment

/*multiple
line commment */

/* js statements :
value, operator, expression, keyword & comment */

// variable declaration
var x = 1; // number (integer)
var y = 1.2; // number(float)
var s = “Hello”; // string
var p = ‘World’; // string

// = assingment operator
// arithmetic operator
var a = 6;
var b = 2;
console.log(a + b); // 8
console.log(a – b); // 3
console.log(a / b); // 3
console.log(a * b); // 12
console.log(s + ” ” + p); // concat

// case sensitive
var firstName = ‘Hezrul’;
console.log(firstName); // undefined

var last_name = ‘Hezrul’;
var state = “Negeri Sembilan”;
console.log(last_name + ‘ ‘ + state);

var $country = “malaysia”;
var _price = 5.60;
console.log($country + ‘ ‘ + _price);

// string operator
var text1 = “John”;
text1 += ” Doe”; // text1 = text1 + ” Doe”;

console.log(text1);

// comparison operator
// >, <, >=, <=, ==, !, !=, ===, !==
if(a > b) {
console.log(“a greater than b”);
}

if(1 === “1”) { // not true
console.log(“equal value and equal type”);
}else {
console.log(“equal value”);
}
//ternary operator
// variableName = (condition) ? true : false
var age = 10;
var voteable = (age < 18 ) ? “Too young” : “Old enough”;
console.log(voteable); // Too young

// array
var cars = [“Proton”, “Volvo”, “BMW”];
// var cars = new Array(“Proton”, “Volvo”, “BMW”);

// access the elements of an Array
console.log(cars[0]);
console.log(cars[1]);
console.log(cars[2]);

var person = [‘John’, ‘Doe’, 46];
console.log(“Name : ” + person[0] + ‘ ‘ + person[1] + “\nAge : ” + person[2] );

console.log(person);

// array properties & methods
console.log(cars.length); // 3
console.log(person.length);
person.push(“US”);
console.log(person); //[“John”, “Doe”, 46, “US”]
person.pop();
console.log(person); //[“John”, “Doe”, 46]

// associative array
var student = [];
student[‘firstName’] = “Hezrul”;
student[‘lastName’] = “Mifzal”;
console.log(student);
console.log(student.length); //0
console.log(student[0]); // undefined
console.log(student[‘firstName’]); //Hezrul

// loop
for (i = 0; i < cars.length; i++) {
console.log(cars[i]);
}

cars.forEach(function(element, index){ // php foreach($arr as $key => $value)
console.log(index + ” => ” + element);
})

//isStrind, isInt,
if (Array.isArray(cars)) {
console.log(‘variable cars is array’);
}

if(cars instanceof Array){
console.log(‘variable cars is array’);
}

console.log(typeof cars); // object

Leave a Reply

Your email address will not be published. Required fields are marked *