JavaScript file

Arrays and strings in JavaScript. Basics part 5 — summary.

After discussing the absolute basics, it’s time to talk about arrays and strings in JavaScript. These are really important elements, and having mastered them we are ready to go to the next level.

Arrays and strings in JavaScript

At first we’ll take a look at text strings and basic methods of processing them. Afterwards we’ll discuss the arrays.

Personally I really like coding something related with strings and/or arrays.

The text is supported by the String class (type). This class allows us to create objects that contain strings; chars and subtitles. Also provides a lot of methods to operate on these strings:

anchorreplace
bigsearch
blinkslice
boldsmall
charAtsplit
charCodeAtstrike
concatsub
fixedsubstr
fontcolorsubstring
fontsizesup
indexOftoLowerCase
italicstoSource
lastIndexOftoUpperCase
linktoString
matchvalueOf

Example — working with strings:

var str = new String("Hi JavaScript!");
document.writeln("Our string: " + str.italics() + " has "
    + str.length + "chars length");

Using the dot operator we call the method of the String class, associated with our object (string).

The + operator is used to connect the strings. Of course in the context of String type. For the numbers it’s just operation of summation.

Example — split the string by a separator:

var tab = "ab-cd-ef-gh".split("-");
for (index in tab) {
    document.write(tab[index] + "<br />");
}

For example, such effect in PHP is reachable by the explode() function.

Example — operations on a string (then anchor method):

var str = new String("abc");
// puts str to the <a> markup:
// <a name="myname">abc</a>
var str = "abc".anchor("myname");

Methods for processing strings

Below we described frequently used methods of the String class:

charAt — returns the character located within the index specified by the argument:

var c = "abc".charAt(1);

charCodeAt — returns the character code:

var code = "abc".charCodeAt(1);

concat — string concatenation:

var str1 = "A"; var str2 = "B";
var str3 = "123".concat(str1, str2); // result: 123AB

Loops in JavaScript, conditional statements, flow control. JavaScript basics part 4.

In today’s article we’ll discuss conditional statements and loops in JavaScript. Thus we have a full understanding of the program flow control.

We are approaching the end of JavaScript basics. And that’s great, because at next development stages there will be more fun and possibilities!

best Valorant cheats

The conditional statement: if

So code execution depending on the condition.

Syntax:

if (state) {
    operation;
}

where the ‘state’ is tested expression, and it must be true to execute the ‘operation’. To test for false we use negation:

if (!state) {
    operation;
}

In this case the ‘operation’ will be executed if the ‘state’ will be false.

Example — if, else statements:

var x = 1, y = 2;

if (x == y) {
    alert('Values are equal');
} else {
    alert('Values are NOT equal');
}

Example — if, else if, else:

window.age = prompt("How old are you?", "");
txt = "";
if (age <= 17) {
    txt = "Too young for a beer!";
}
else if ( (age > 17) && (age <= 100) ) {
    txt = "Cheers!";
}
else {
    txt = "You shouldn't drink a beer.";
}

alert(txt);

The code above will create a variable “age” that will contain a value specified by the user (taken via the prompt function). Then the final message will be created, depending on this value taken from the user.

The conditional operator ?:

This operator has not been discussed in the previous article. The conditional operator ?: allows to define a value, which will be returned depending on the conditional expression. In other words, the developer can write conditional statements more succinctly than when using if statements.

Syntax: condition ? value_for_true : value_for_false;

Example:

var a = 4;
var b = 3;
res = (a == b) ? 'Values are equal' : 'Values are NOT equal';
alert(res);

The expression must return a value of true or false.

The switch statement

It’s just another way of writing conditions. The code is executed depending on a value assigned to the expression. It’s also a way to get concise code.

Syntax:

switch (expression) {
    case val:
        code1;
    break;
    case val2:
        code2;
    break;
    default: code3;
}

Operators in JavaScript, data types, global elements. Part 3 of language basics.

Welcome to the next article about JavaScript basics. Today we’ll focus on very important topics, such as data types and operators in JavaScript.

Operators in JavaScript

They serve the programmer to perform basic operations on variables, like assignment, arithmetic, comparison, and more.

Arithmetic operators

This looks the same as in other programming languages:

+ (addition)
(subtraction)
/ (division)
* (multiplication)
% (modulo division — the division remainder)
++ (incrementation — increase of 1)
– – (decrementation — decrease of 1)

So that is basic math.

Example — arithmetic operations in JavaScript:


var x = 2, y = 3, result = 0;

result = x + y;
alert('2+3 = ' + result);

result = x / y;
alert('2/3 = ' + result);

result = x % y;
alert('2%3 to: ' + result);

y++; // y--;
alert(y);

2/3 is 0.66… and here we can see the essence of data types. If the result would be assigned to int (integer) variable, we would obtain 0. However, typing is done by JavaScript (dynamic typing).

Logical operators

They are used to express the logic conditions:

! — negation of logical value
&& — conjunction (“and”)
|| — logical alternative (“or”)

For example:

if (!a) {
  // negation - NOT operator
}

if (a > 0 && b > 0) {
  // conjunction - AND operator, both conditions must be true
}

if (a >= 1 || b >= 1) {
  // alternative - OR, at least one of conditions must be true
}

Comparison operators

As the name suggests, they are used to compare the values:

== (equal)
=== (identical; not only values, but also data types are compared; we can find this operator also in PHP)
!= (different)
!== (not identical)
< (less than)
<= (less than or equal)
> (greater than)
>= (greater than or equal)

Usage already shown in the previous example.

Bitwise operators

They are used to operate on bits.

Bitwise operators are: ~, &, |, ^, <<,>>,
and >>> i.e. unsigned right shift.

Note: bitwise operators we will describe in details in one of further articles.

Assignment operators

So, how to assign values ​​to variables:

= (assigning values)
+= (increasing the value of a variable and assigning it to the variable on the left)
-= (decreasing the value of a variable and assigning it to the variable on the left)
*= (multiplying the value of a variable and assigning it to a variable on the left)
/= %=  — dividing (and modulo dividing) value of a variable and assigning it to a variable on the left.

Other operators in JavaScript

The language provides more operators:

, (comma — separating arguments)
. (dot — access to a property or method of an object: object_name.element)
new (creating a new object)
delete (deleting an object, particular element of array, etc)
?: (conditional operator — we will write more about it in the next article)
typeof the_name (returns the text name of the operand, specifying its type)

As we are around typeof topic, let’s talk about data types.

Data types in JavaScript

The language gives us a possibility of working on following, basic data types:

– numbers (Number)
– strings (String)
– boolean values — true and false (Boolean)
– objects (Object)
– arrays (Array)
– and special: null and undefined

Functions and events. JavaScript basics part 2.

Functions and events in JavaScript …

… will be the main topic in this part of articles about JavaScript basics.

So let’s go.

Functions in the JavaScript

Functions are the next important element of the language. As we already mentioned in part 1: functions exist independently, while methods are directly associated to the objects.

When we define a function, we can call it, or assign to the events that we want to capture and handle. Capture is possible through assign event handling to element(s) of the website. Both cases demonstrated below.

Example — definition of the function and its call:

function square(number) {
  result = number * number;

  return result;
}

function compute() {
    var k = square(2); // call the square() function
    alert("Square of 2 is: " + k);
}

// call the compute() function:
compute();

The compute() function, that doesn’t return any value, is similar to constructions known from other programming languages, called procedures.

The great feature in JavaScript is the possibility of assigning functions, in the same way as assigning a value.

Example — assign function to the event:

window.onload = function() {
    alert("The window says Hi after load");
}

This (unnamed) function has been assigned to the onload event.

JavaScript file

JavaScript in a nutshell — keywords. Basics part 1.

Welcome to the first part of articles about JavaScript language basics. At the beginning I want to describe things useful for beginners, to start programming as soon as possible. More advanced programmers simply may use it as some kind of handbook, having information in one place.

We’ll start from JavaScript language keywords. The history of JavaScript is interesting, but I won’t write about this topic here, as I want to focus on more practical things.

The list below contains reserved words in JavaScript. Many of them (marked with a star) are reserved for future compatibility. In short words: many of them will be officially supported in future versions of the language. Probably we don’t have to wait too long. And these words are well-known by Java programmers for sure.

Here is the full list:

abstract (*)as (*)boolean
breakbytecase
catchcharclass (*)
continueconst (*)debugger (*)
defaultdeletedo
doubleelseenum (*)
export (*)extends (*)false
finalfinallyfloat
forfunctiongoto (*)
ifimplements (*)import (*)
ininstanceofint
interface (*)is (*)long
namespace (*)native (*)new
nullpackage (*)private (*)
protected (*)public (*)return
shortstatic (*)super (*)
switchsynchronized (*)this
throwthrows (*)transient (*)
truetrytypeof
use (*)varvoid
volatile (*)whilewith

The matter of embedding scripts in page source

A few words about how to embed scripts.

According to XHTML:

<script type="text/javascript">
//<![CDATA[
  document.write("Hello!");
//]]>
</script>
Power

JavaScript — for what and why? Motivation to explore the language.

JavaScript? I’m pretty sure we can find full spectrum of people — from passionate enthusiasts to people that hate this language, and despise JS developers.

Meanwhile, in good conscience we can say that JavaScript is more powerful than many people think!

Let’s try to answer following questions:

  • Is JavaScript so strong and necessary?
  • Isn’t this a language of a worse category?
  • Isn’t the “JavaScript Developer” worse than other developers?

Well …

  • Yes!
  • No!
  • No!

JavaScript has got rid of the complexes long time ago!

Today, JavaScript is a real toolbox of almost all Web Developers. I remember old times, when JavaScript was associated with the low-quality scripts, with different behavior in many browsers, when the “JavaScript Developer” wasn’t a real software developer.

Maybe it was partially true, because of big amounts of scripts written by (sometimes very beginner) coders. Later such creature has been modified by others, and … effects are well known for everyone, who remember old “good” times before JavaScript frameworks 🙂

That small piece of the history I know also from my own experience. And additionally from the point of view of both sides, because I also know and like other programming languages. And I admit, I had small episode when I seen JavaScript as “the language of a worse category”.

Happily now I know how many possibilities we can find around this language.

The old days are gone, Internet has become much more commercial, and JavaScript had the real era of rebirth.

First of all, due to AJAX (Asynchronous JavaScript and XML). Also we said goodbye to annoying differences of handling JavaScript in many web browsers.

So now the programmer can just focus on creating the final effect, instead of wasting valuable time on creating dozens of workarounds.

JavaScript is growing in popularity and will continue to grow

Let’s take a look on tools like the TIOBE Index.

In a nutshell: this index is based on the number of information searches about the language (each Turing complete language) in search engines.

JavaScript, as any other language, experiencing its ups and downs. But generally we can expect a growing trend for this language.

TIOBE index: JavaScript trend, Jul 2013

TIOBE index: JavaScript trend, Jul 2013

Why?

And because JavaScript is standard and most important client-side programming language. It has no equal when it comes to manipulation of the document or the browser window.

Furthermore it appears in isolation from typical web browsers, to be a part of Runtime Environments. The great example is Adobe AIR, which allow us to create desktop applications using JavaScript (and HTML + CSS).

Hello JavaScript World!

Welcome dear readers! This is the first entry on the javascript-html5-tutorial.com blog.

With this short introduction we want to say hello.

We decided to start a new blog about JavaScript and HTML5. But you can be sure it will be created with a passion.

JavaScript language (especially with HTML5) is more and more powerful, and we are very happy with this. Some of newer JavaScript possibilities are really exciting.

From this place we want to ensure you, that the blog will be developed in the long term perspective. When developing it for readers, we develop ourselves. This is very valuable for us.

And we have planned very wide spectrum of topics (and source codes of course) to describe and publish. The quality is our attitude, and we hope we won’t disappoint the reader.

So let’s say traditional Hello World (in JavaScript language :-)):

alert("Hello JavaScript World!");

That’s all for the moment. More information about the blog you can find on About Us page.

We hope that use this blog will be pleasant for you — at least as pleasant for us is creating it.