
Play Store Application link – Java to JavaScript in 13 Steps – App on Google Play
In programming, data types define what kind of data a variable can hold. Think of a variable as a box that stores values.
Data Types in JavaScript
Here’s a quick overview of JavaScript data types with Java comparisons:
- String: Similar to
String
in Java. It holds text.
let greeting = "Hello World"; // Equivalent to String greeting = "Hello World";
- Number: Represents numerical values, like Java’s
int
ordouble
.
let age = 42; // Similar to int age = 42;
- Boolean: Represents
true
orfalse
, similar to Java’sboolean
.
let isStudent = true; // Equivalent to boolean isStudent = true;
- Null: Represents the intentional absence of any value, similar to
null
in Java.
let x = null; // Same as Object x = null;
- Undefined: A variable that hasn’t been assigned a value yet. Unlike Java, which requires variable initialization, JavaScript variables are
undefined
if not explicitly set.
let y; // Equivalent to a Java variable declared but not initialized.
- Object: A complex data type that can hold multiple values in a single entity, like Java’s classes.
let person = { name: "John", age: 30 }; // Similar to a Java class instance with properties
- Symbol: A unique value that can’t be changed, which is a bit different from Java’s typical types but useful for unique keys in objects.
let id = Symbol(); // Unique identifier, similar to unique ID generation in Java
Example Program
Here’s how you might declare and use these data types in JavaScript:
// Declare a string variable
let message = "Hello World";
// Declare a number variable
let age = 42;
// Declare a boolean variable
let isStudent = true;
// Declare a null variable
let x = null;
// Declare an undefined variable
let y;
// Declare an object variable
let person = { name: "John", age: 30 };
// Declare a symbol variable
let id = Symbol();
// Print all variables to the console
console.log(message);
console.log(age);
console.log(isStudent);
console.log(x);
console.log(y);
console.log(person);
console.log(id);
Output:
Hello World
42
true
null
undefined
{ name: 'John', age: 30 }
Symbol()
Running the Code in Visual Studio Code
To see your JavaScript code in action, follow these steps (similar to running Java programs):
- Open Visual Studio Code: Like launching your Java IDE.
- Create a New File: Save it with a
.js
extension (e.g.,data_types.js
). - Copy and Paste the Code: Insert the code above into your new file.
- Open the Terminal: In VS Code, go to
View > Terminal
. - Run the File: Type
node data_types.js
in the terminal and press Enter.
The output will appear in the terminal window, showing the results of your JavaScript code.