JavaScript

Java Collections
Level 3 , Lesson 1
Available

"Hi, Amigo!"

"Hi, Bilaabo!"

"I'm glad to see you. Today we have a small but very informative lesson. Today I will tell you about the JavaScript language."

JavaScript - 1

"A new language? How interesting…"

"JavaScript is currently popular thanks to the Internet. The fact is that it is the only language that all browsers can execute. If you want to add animation or logic to your web page, then you can do it with JavaScript."

"Is it true that JavaScript is the most popular language?"

"Yes, but it would be more accurate to say that it is the most popular 'second language'. C++, Java, C#, and PHP programmers need to write small scripts in JavaScript to liven up their webpages. But, far fewer people only write code in JavaScript."

"Why is it named JavaScript? It sounds almost like Java."

"Actually, initially, it was called LiveScript, but when Java began to become more popular, it was renamed JavaScript."

"Java and JavaScript are two completely different languages. Don't confuse them."

"Unlike Java, JavaScript doesn't have classes, and doesn't support static typing, multithreading, and much more. Java is like a large set of construction tools, while JavaScript is more like a Swiss Army knife. JavaScript is designed to solve small tasks, but Java is for solving large and very large tasks."

"Here are some facts about JavaScript:"

"The first fact is that JavaScript has functions, but no classes"

"You simply write programs using several functions and that's it. For example:"

JavaScript
function min(a, b)
{
 return a
}
Java
public static int min(int a, int b)
{
return a
}

"New functions are declared using «function <name>».

"Another example:"

JavaScript
function min(ab)
{
 return a < b ? ab;
}

function main()
{
 var s = 3;
 var t = 5;
 var min = min(s, t);
}
Java
public static int min(int a, int b)
{
 return a < b ? ab;
}

public static void main()
{
 int s = 3;
 int t = 5;
 int min = min(s,t);
}

"The second fact is that JavaScript has variables, but those variables don't have types"

"JavaScript is a dynamically typed language. This means that variables actually don't have types. Any variable can be assigned a value of any type (values have types). For example:"

JavaScript
function main()
{
 var s = "Bender";
 var k = 1;
 var n = s.length;
}
Java
public static void main()
{
 String s ="Bender";
 int k = 1;
 int n = s.length();
}

"But dynamic typing increases the risk of runtime errors:"

JavaScript
function main()
{
 var s = "Bender";
 var k = 1;
 var n = k.length;
}
Java
public static void main()
{
 String s ="Bender";
 int k = 1;
 int n = k.length();
}

"In the example above, we used the variable k (an integer) instead of s (a String). In Java, the error would be detected at compile time, but in JavaScript, it won't be caught until later when the code is running."

"If you want to declare a variable in JavaScript, you need to write «var <name>». There are no variable types, and there are no types for methods/functions or their arguments."

"JavaScript has very few strict rules and a lot of anarchy."

"You can declare a function with 5 arguments and call it with two—the rest will just be null. You can declare a function with two arguments, and pass five when you call it. Three will simply be thrown away. There is minimal control over errors, typos, and changes."

"The third fact is that JavaScript has if, for, and while statements"

"JavaScript has if, for, and while. This is great news. Look at these examples:"

JavaScript
function main()
{
 var s = "Bender";

 var result = "";

 for(var i = 0; i < s.length; i++)
 {
  result += s[i] + "";
 }
 if(result.length > 10)
 {
  alert (result);
 }
 else
 {
  while(result.length <= 10)
  {
   result += " ";
  }
  alert(result);
 }
}
Java
public static void main()
{
 String s = "Bender";
 char[] s2 = s.toCharArray();
 String result = "";

 for(int i = 0; i < s.length(); i++)
 {
  result += s2[i] + "";
 }
 if(result.length() > 10)
 {
  System.out.println(result);
 }
 else
 {
  while (result.length() <= 10)
  {
   result += " ";
  }
  System.out.println(result);
 }
}

"They're pretty similar. I think I could figure out how code written in JavaScript works."

"Your optimism is good."

"The fourth fact is that JavaScript supports try-catch-finally blocks"

"JavaScript has exceptions (Error) and that's good. It doesn't have checked exceptions, only unchecked exceptions similar to a RuntimeException. The try-catch-finally construct works the same as in Java. For example:"

JavaScript
function main()
{
 try
 {
  var s = null;
  var n = s.length;
 }
 catch(e)
 {
  alert(e);
 }
}
Java
public static void main()
{
 try
 {
  String s = null;
  int n = s.length();
 }
 catch(Exception e)
 {
  System.out.println(e);
 }
}

"When we try to get the length of the String, an exception will be thrown since the variable is null."

"The fifth fact is that JavaScript has arrays"

"Good news: JavaScript has arrays. Bad news: there are no lists or collections."

"Another piece of good news is that arrays can dynamically expand when new elements are added and decrease as elements are removed. It's more like a hybrid between an array and list."

For example:

JavaScript
function main()
{
 var m = [1, 3, 18, 45, 'c', "roma", null];
 alert(m.length); // 7

 m.push("end");
 alert(m.length); // 8

 for (var i = 0; i < m.length; i++)
 {
  alert(m[i]);
 }
}
Java
public static void main()
{
 List m = Arrays.asList(1, 3, 18, 45,'c', "roma", null);
 System.out.println(m.size()); // 7

 m.add("end");
 System.out.println(m.size()); // 8

 for (int i = 0; i < m.size(); i++)
 {
  System.out.println(m.get(i));
 }
}

"What are those square brackets in the array declaration?"

"That's exactly what an array declaration is. To declare an array, you need to write square brackets. Then you list the elements of the array in between the brackets. You declare an empty array simply with a pair of brackets."

Example
var m = [];

"The sixth fact is that JavaScript has objects"

"JavaScript has objects. In fact, everything in JavaScript is an object, even primitive types. Each object is represented as a set of key-value pairs. Roughly speaking, every JavaScript object is equivalent to a HashMap in Java. Here's an example of an object declaration:"

JavaScript
function main()
{
 var m = {
  first_name : "Bill",
  last_name: "Gates",
  age: 54,
  weight: 67,
 children: ["Emma", "Catrin"],
 wife: {
  first_name : "Melinda",
  last_name: "Gates",
  age: 45,
  }
};

 alert(m.first_name); // Bill
 alert(m.age); // 54
 alert(m.wife.first_name); // Melinda

 m.age = 45;
 m.age++;
 m["first_name"] = "Stive";
 m["wife"] = null;
Java
public static void main()
{
 HashMap m = new HashMap();
 m.put("first_name", "Bill");
 m.put("last_name", "Gates");
 m.put("age", 54);
 m.put("weight", 67);

 String[] children = {"Emma", "Catrin"};
 m.put("children", children);

 HashMap wife = new HashMap();
 wife.put("first_name", "Melinda");
 wife.put("last_name", "Gates");
 wife.put("age", 45);
 m.put("wife", wife);

 System.out.println(m.get("first_name"));
 System.out.println(m.get("age"));

 HashMap w = ((HashMap)m.get("wife"));
 System.out.println(w.get("first_name")));

 m.put("age", 45);
 m.put("age", ((Integer)m.get("age")) + 1);
 m.put("first_name", "Stive");
 m.put("wife", null);

"To create a new object, you just have to write two curly braces: «{}»."

"Inside the braces, you can specify object data in the following format: «key, colon, value, comma»."

"Object fields can be accessed in two ways:"

Equivalent statements
m.age = 45;
m[“age”] = 45;

"If the specified field doesn't exist, then it is created."

"My relief valve is overloaded or something. I think we should take a break."

"The seventh fact is that JavaScript was created to work inside web pages."

Comments (7)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Hoist Level 38, San Diego, United States
11 January 2024
a) "The first fact is that JavaScript has functions, but no classes" b) "The second fact is that JavaScript has variables, but those variables don't have types" c) "The third fact is that JavaScript has if, for, and while statements" d) "The fourth fact is that JavaScript supports try-catch-finally blocks" e) "The fifth fact is that JavaScript has arrays" f) "The sixth fact is that JavaScript has objects" g) "The seventh fact is that JavaScript was created to work inside web pages."
Justin Smith Level 41, Greenfield, USA, United States
26 September 2022
Have fun debugging Javascript. It's madness!
Andrei Level 41
25 June 2021
I think JavaScript was written by a mad person, to be used by mad people... No types on variables, arrays of various types... 💀👻
Jakub M Level 32, Ostrava, Czech Republic
11 August 2021
And that's the time when TypeScript is going to help 😍 As far as I know it rook only 10 days to create JS (only 1 person), which is quite impressive but on the other hand there were "simplifications" when the language was created. For example "var" as showed above shouldn't be used - it is safer to use "let" or "const"...
MaGaby2280 Level 41, Guatemala City, Guatemala
1 June 2021
Nice introduction to JavaScript
JianQiu Hwang Level 35, Washington
16 March 2020
You can test these JavaScript code in the console tab of the DevTool in Chrome.
Lisa Level 41
31 December 2021
Just use IntelliJ to test the code. Create a new html file. IntelliJ automatically creates the structure. Now just add two script tags. For simplicity just put them inside the body tags. One to hold the script you want to test. The other starts the method you just declared, eg:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test JavaScript</title>
</head>

<body>
<script type="text/javascript">
function sayHello(text)
{
    alert("Hello " + text)
}
</script>
<script>
    window.onload=sayHello("CodeGym")
</script>
</body>
</html>
On the top right in your code window browser icons will appeare, click one to open the html code with the browser of your choice