3

I'm making a simple list with nodes and I want to add an attribute of the same type to the class. When I was programming in Java I did it like that:

public class Node {

   public  char date;
   public Node next; 

   public Node(char date) 
   {
       this.date = date;
   }
}

But, in javascript it only allows me to use var variables. How do I create a variable of the same type of class that I want?

I remain attentive to comments...

felixmosh
  • 32,615
  • 9
  • 69
  • 88
  • 3
    There are no classes and types in javascript. Your `var` can be anything, it does not have a type. Just a value. – Twometer Aug 20 '18 at 20:54
  • 2
    js is loosely typed. There's no such thing. You can use typescript, which supports typed variables. Note that you should use `let` or `const` instead of `var` – baao Aug 20 '18 at 20:55
  • 1
    Possible duplicate of [Declaring javascript variables as specific types](https://stackoverflow.com/questions/14202743/declaring-javascript-variables-as-specific-types) – kashalo Aug 20 '18 at 20:58
  • 1
    Read up on closures – seebiscuit Aug 20 '18 at 20:58

3 Answers3

3

Although JavaScript is object-oriented language, historically, it isn't a class-based language—it's a prototype-based language. There are subtle differences between these two approaches.

Nevertheless, in 2015, with ECMA script 6, classes have been introduced. Now it is correct to use classes like any other class based languages such as Java

More here: Does JavaScript have classes?

You have other options too, use a strongly typed language like typescript and transpile it to Javascript

so-random-dude
  • 15,277
  • 10
  • 68
  • 113
2

In Javascript types are "infered" here's an example

class Node {
   constructor(date) {
     this.date = date
   }
}
var foo = new Node(new Date());
// foo instanceof Node => true
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

In Javascript, you can use var (variables declared like this can be redeclared and reassigned values), let (variables declared like this can not be redeclared but can be reassigned values), or const (variables declared like this can not be redeclared or reassigned values) to define variables. You can not declare the type of a variable--only its value (which can be of any type) as Javascript is an untyped language.

If you want to enforce the type a particular argument for a function, you can use typeof to check the type of the provided argument(s) and throw an Error if it is not the correct type.

function add(num1, num2){
  if(typeof num1!=="number"||typeof num2!=="number"){
    throw new TypeError("You must provide numbers!");
  }
  return num1+num2;
}
console.log(add(1,2));
add("string", {});

If you want to use typed variables, consider using Typescript.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80