[Go to site: main page, start]

0% found this document useful (0 votes)
19 views5 pages

JavaScript Primer Overview

Uploaded by

cosmotraumatika
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views5 pages

JavaScript Primer Overview

Uploaded by

cosmotraumatika
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript Primer

To learn more JavaScript, please check out these links:


1. [Link]
2. [Link]
3. [Link]
4. [Link]

While we don’t have enough space here to cover JavaScript completely,


here is a quick overview for those familiar with other programming
languages to get started. To experiment with JavaScript, you can use the
JavaScript console supplied with your favorite browser or startup [Link]
to run the Read-Eval-Print-Loop (REPL) on your machine.

Variables

Variables are declared as follows:


var myFirstVariable;

Declarations can be separated by commas on the same line:


var myFirstVariable, mySecondVariable;

They can be assigned with some initial values using the equals operators.
var myFirstVariable = 0;

Types

JavaScript supports various types as follows:


var anInt = 0;
var aFloat = 2.5;
var aBoolean = true;
var aString = “This is a string”;
var anArray = [1,2,3];
var anObjectLiteral = {
someField : “Some value”
};
var aFunction=function() { return; }; // function
var re = /ab+c/; // regular expression

You can instantiate an object using the new operator like this:
var aDate = new Date();

Comments

Comments can use the double slash single line or the C-style multiline
comment format:
// this is a single line comment
/*
This is a multi-line comment
*/

Basic Operators

The built-in numerical operators include the usual: + (addition), –


(subtraction), / (division), * (multiplication) and % (modulo).
var a = 6;
a = a + 1; // a is 7
b = b % 2; // b is 3
a++; // a is 8
a–; //a is 7
a += 3; // a is 10

Strings can be concatenated as shown:


var aString = “The value of a is ” + a;
var greeting = “What a very “;
greeting += “nice day”;

The typeof operator returns the type of a variable.


typeof aString; // returns “string”

To determine the class of an object, for example, to distinguish between


arrays and other objects, the [Link] method can be used as
follows:
[Link](new Date()); // “[object Date]”
[Link]([1,2,3]); // “[object Array]”
[Link]({someField:12}); //”[object
Object]”
[Link](function(){return;}); //”[object
Function]”

Conditionals

You can use the comparison operators, < (less than) > (greater than) <=
(less than or equal) >= (greater than or equal) == (equals) != (not equals) in if
statements as follows:
var a = 1;
var b = null;
if (a > 0) {
b = “a is greater than zero”;
} else {
b = “a is zero or less”;
}

To shorten this, one could use the conditional operator as follows:


var b = (a > 0) ? “a is greater than zero” : “a is zero or
less”;

Loops

Javascript supports for and while loops:


for (var i = 0; i < [Link]; i++) {
[Link](myArray[i]);
}
while (x < 10) {
[Link](x++);
}

Functions

Functions are created like this:


function addOne (x) {
return x + 1;
}
To call a function, you can call them as follows:
var y = addOne(5); // y = 6

Or, if the function is a method of an object, for example, a Date object:


var d = new Date();
var year = [Link](); // returns 0 for January, 1 for
February,

Callbacks

[Link] is an event-based framework with only one thread of execution. To


allow more than one task to execute while performing I/O or waiting for a
timer to expire, callbacks are used extensively. For example, to log ‘done’
to the console after 2 seconds, you can use an anonymous function
callback as follows:
setTimeout(function() { [Link](‘done’); }, 2000);

You can use functions to process an array:


var friends = [“mike”,”roberto”, “rodger”, “ted”, “daniel”];
[Link](function (eachName, index){
[Link](index + 1 + “. ” + eachName); // 1. mike 2.
roberto 3. rodger 4. ted 5. daniel
});

Exception Handling

Exception handling can be used to catch errors in your code. To do so,


wrap your code in a try/catch block as shown.
try {
// try to do something
} catch (e) {
// handle errors
} finally {
// this block is always executed regardless of whether there
was an exception
}
That’s the end of this JavaScript overview. Those new to JavaScript should
now have enough knowledge to get going. If you feel you don’t understand
the JavaScript, it’s worthwhile taking a look at one of the many JavaScript
primers mentioned at the start of this primer.

Common questions

Powered by AI

JavaScript supports 'for' and 'while' loops for iteration. A 'for' loop iterates a set number of times with a counter, like 'for (var i = 0; i < anArray.length; i++) { console.log(anArray[i]); }'. A 'while' loop continues as long as a condition is true, such as 'while (x < 10) { console.log(x++); }'. These loops facilitate repeated execution of code blocks.

In JavaScript, a function is defined using the 'function' keyword, followed by a name and parentheses for parameters. For example, 'function addOne(x) { return x + 1; }' defines a function 'addOne' that takes one argument 'x'. To call the function with an argument, use 'addOne(5)', which returns 6.

The 'conditional operator' in JavaScript, also known as the ternary operator, offers a shorthand for writing if-else statements. It uses the syntax 'condition ? expressionIfTrue : expressionIfFalse'. For instance, in the expression 'var b = (a > 0) ? "a is greater than zero" : "a is zero or less";', if 'a > 0' evaluates to true, 'b' is assigned "a is greater than zero"; otherwise, it is "a is zero or less".

In JavaScript exception handling, the 'try' block is used to encapsulate code that may throw an exception. If an exception occurs, control is transferred to the 'catch' block, where the error can be handled. The 'finally' block is always executed regardless of whether an exception was thrown or caught, typically used for cleanup operations.

JavaScript uses the 'typeof' operator to determine the type of a variable, which returns values like 'string', 'number', 'boolean', etc. For more precise type checking, particularly to differentiate between arrays and other object types, JavaScript uses 'Object.prototype.toString.call'. For example, 'Object.prototype.toString.call([1,2,3])' returns '[object Array]', allowing arrays to be distinguished from other objects like '[object Object]'.

JavaScript supports two types of comment syntax. Single-line comments use a double forward slash, for example, '// this is a single line comment'. Multi-line comments begin with '/*' and end with '*/', as in '/* This is a multi-line comment */'. These comment syntaxes allow developers to include explanatory notes or temporarily disable code.

The 'typeof' operator in JavaScript is used to identify the primitive data type of a variable, returning strings such as 'undefined', 'string', 'number', 'boolean', and 'object'. In contrast, 'instanceof' checks for object type by verifying if an object is an instance of a specific constructor. For example, '[] instanceof Array' returns true. 'typeof' is for basic type checking, while 'instanceof' is used for complex objects.

The 'forEach' method in JavaScript executes a provided function once for each array element, offering a clean and concise syntax for array iteration. For instance, 'var friends = ["mike", "roberto", "rodger"]; friends.forEach(function(eachName, index) { console.log(index + 1 + ". " + eachName); });' iterates over 'friends' and logs elements with their indices. This improves code readability over traditional for loops.

JavaScript's built-in numerical operators include '+' (addition), '-' (subtraction), '*' (multiplication), '/' (division), and '%' (modulo). These operators perform arithmetic operations, such as 'var a = 6; a = a + 1;' which increases 'a' from 6 to 7. Increment and decrement operations are simplified with 'a++' and 'a--'.

In Node.js, callbacks are extensively used to handle asynchronous operations, allowing the non-blocking event model to function efficiently despite having a single execution thread. A callback function is passed as an argument to another function, and is executed once the asynchronous operation completes. For example, using 'setTimeout' to log 'done' after a delay, as in 'setTimeout(function() { console.log('done'); }, 2000);', demonstrates how callbacks enable code to continue executing while waiting for timed events to complete.

You might also like