Is there a need to initialize variables that are passed as a "class" constructor arguments in Javascript? - javascript

I come from a Java background, where everything is Object Oriented. While Getting into a bit more of Javascript (more into the class areas of javascript), I've noticed complete changes. The biggest for me is getting used to the prototyping of the so-called "classes" javascript has. So, my question is if you need to intialize the varialbes you pass into your class function constructor method-thing. For example:
function Foo(a, b, c) {
this.a = a;
var b = b;
this.c = "";
this.d = a + b;
}
Now In javascript is this necessary? Cause in Java, you have to show that the variable type definition in the argument itself: Foo(int a, int b, string c) Now how does the method in Javascript know what type of data structure it is being passed too? Like what if they passed in an array for a, and then my code tried to add the integer and the array together? That won't push the int too the array will it?
Sorry for being a bit questiony, I've been looking for an answer for a while on the Google... And it's getting late here.
Thanks for any help
Uneveris

So, my question is if you need to intialize the varialbes you pass into your class function constructor method-thing.
Do they need initializing, no. Javascript is a loosely typed language and declared variables can be of any type.
You do not need to declare a variable type for the arguments, they can be anything. Also note the vars are private variables in the scope of the constructor.
Now how does the method in Javascript know what type of data structure it is being passed too?
As a result of loose types, javascript has a type typeof to help work out what a variables type actually is if strong typing is required.
if (typeof this.a !== 'function')
throw "Expected a function, received a " + typeof this.a;
Verbose, but it fulfils its purpose.
typeof reference
Like what if they passed in an array for a, and then my code tried to add the integer and the array together? That won't push the int too the array will it?
Have you tried to do this?
var a = new Array();
var b = 1;
var c = a + b;
console.log(typeof c);
>> string
In Node.js the output is a string with the array values concatenated and the integer appended as a string on the end.
It is important when expecting a specific data structure that data you have been passed is what you are expecting. In JS, this is by conditionally checking.
If you are writing these classes purely for your self, duck typing can be useful. If it looks like a duck, quacks like a duck then it is a duck. This is to do with semantics when working in a loosely typed language like JS. Two assumptions === true.
What is duck typing
Hope this helps answer your questions.

You can't be sure what parameter types are being passed to your method. That is a main Javascript language trait which can be used for both good and bad.
So, what happens if there are wrong parameter types? Javascript will try to silently convert them to something common.
For example:
var a = [100,2,3];
var b = 5;
var c = a + b;
Adding an array and an integer (as well as string) will result in a string "100,2,35". Note that array is first converted to String, then 5 is simply appended to the end. This behaviour closely resembles the Java's one, that calls a toString() method of any object whenever it needs to concatenate.
You can avoid the wrong types in two ways. First, convert them yourself. Like,
a = Number.parseInt(a, 10); // now a is of type number
Second, if your method is important and highly dependent on the data correctness, you should not convert the params but avoid using them at all if they are of wrong type:
if (typeof a != "number") throw "Param must be int";
Finally, you can see this JS framework that supports strict typing:
http://betterjs.org/

Related

specify the result of a function in javascript

Am not sure if functions in javascript are what we call methods in other programming languages.Methods in other programming languages can have their result specified just after the access-specifier like in C# for example i would do like
//method to return int
private int myinteger(){
int a=0;
return a;
}
//method to return string
private string mystring(){
string b="myreturn";
return b;
}
I just don't know how to do that with javascript functions, you think you can help me with a sample?Thank You very much :)
You don't need to provide the data types in javascript. The functions are pretty similar you just have to start it with the function keyword.
Also, we need to start the variables with const or let.
I use the console.log(myinteger()); below to log the value of the myinteger() function in the browser console. (Similar to c++'s cout)
//method to return int
function myinteger() {
const a = 0;
return a;
}
//method to return string
function mystring() {
const b = "myreturn";
return b;
}
console.log(myinteger());
console.log(mystring());
If you are someone who wants to use javascript but still want to assign the data type and many more thing then you can use TypeScript By Microsoft.
You cannot do this with javascript, but you still have two workarounds available:
Use eslint and use the https://eslint.org/docs/rules/consistent-return rule
Use typescript
Javascript has types for values (not variables)
so you can define a variable as
var name = "Hamond";
and to know it's type you have to use typeof
typeof name; // "string"
Side note: you can use let or const instead of var but let that be for another time.
so variables in javascript doesn't have types, values have.
You can add static typing using typescript so
var name: string = "Hamond";
and at dev time if you wanted to edit name and incorrectly deal with it as a non string type you will get an error
warning you immediately
name = 3; // error
name - 4; // error
// and so forth because `name` is of `string` type
so this type check is done at author or dev time and you don't have to wait until run time to get the error.
Why all the talk about variables and values?
Because Javascript function can return any value(even returning a variable is basically returning its value if it's scalar value or its reference if it's an object type)
so defining a function look like:
function doSomething(){
return 33;
}
notes:
no return type
can have no return statement(by default will return undefined)
with typescript
function doSomething(): number{
return 33;
}
typing problems solved at dev/write time
About function vs method:
I think developers in many times use these terms interchangeably, but in javascript we just have function, even a function defined inside a class in javascript is just a function. People like the name method when its defined inside some class.
references:
JS syntax
The Nature Of Functions

Javascript - Which data is stored in "var" and how its content/storage is changed

I'm learning JS and quite confused about variables:
Short Story: How browsers determine the type of data under var tag, how they determine storage requirements for the type of data under var tag, what happens when two different types of data are assigned one-after-another to the same variable and why these variables're all warped up under var name? It would make more sense if JS had different types of data as integers, strings etc.
Long Story:
Normally, when we want to declare a variable, we define its type: integer, string or char etc. This way, we make sure enough storage is allocated for variable and most of the time, there're some special functions for that specific variable type. In JS, variables -and apparently functions too- are simply used under var name. So, we store anything under var name. My question is this: how browsers/JS compilers differentiate types of data in variables as string/char etc, how they decide the bit-length required for that data, and how they handle which functions will suit that data? What happens when I assign an integer to that variable first, then a string later? Also, wouldn't it be easier to define different types of variables?
I'm a beginner on JS, so go easy on me please. Cheers!
JavaScript variables are not typed but their values do have a type. The same variable can be assigned new values.
var i;
console.log(typeof i);
i = true;
console.log(typeof i);
i = 0;
console.log(typeof i);
i = "hello";
console.log(typeof i);
As far as the memory allocation is concerned, its nicely explained here.
Javascript is loosely-typed. Which means variables don't have a specific type for the developer. This doesn't mean a variable has no type for the system.
Let's look at the following example:
var string = "foo";
var number = 2;
var boolean = true;
var object = {rhymes: "on blue"};
console.log(typeof string); //string type
console.log(typeof number); //number type
console.log(typeof boolean); //boolean type
console.log(typeof object); //an object
//you can also "reassign" a new type to a variable just by reassigning a new value:
var string = 2;
console.log(typeof string) //number type
Here you see that the system does in fact know the type of the variable.
The system also doesn't care that much about the type. Like a string or object doesn't have a pre-defined bit length because their value and/or length is arbitary.
This, let's call it feature, is a great benefit of Javascript but it can be a pain in the a** as well.
If you want to use the best part of both, loosely-typed and strongly-typed (if you have to define a type) you should learn about Typescript. This is just a superset of Javascript that compiles to plain Javascript but offers types.
This is really broad, so I will break it down.
How browsers determine the type of data under var tag
The JavaScript Runtime Engine can determine the variable type by the type assigned, either a literal or another variable. This is different than a compiled language that requires type information at compile time, before runtime.
How they determine storage requirements for the type of data under var tag
This is partially defined in the spec, partially implementation specific. For example var i = 0 is a number but how that is implemented depends on the JavaScript Runtime Engine.
What happens when two different types of data are simultaneously assigned to the same variable and why these variables're all warped up under var name?
You actually can't assign at the same time, but you can assign one after the other. When you assign the second time, the value and the type are changed!
var o = 5; // variable 'o' is a number with value 5
o = 'Hello'; // variable 'o' is a string with value 'Hello'
o = {foo: 'bar'}; // variable 'o' is an object with value {foo:'bar'}
It would make more sense if JS had different types of data as integers, strings etc.
JavaScript does have different types!
JavaScript is a loosely typed or a dynamic language. That means you don't have to declare the type of a variable ahead of time. The type will get determined automatically while the program is being processed.
Example:
var o = 5;
console.log(typeof o); // number
o = 'Hello';
console.log(typeof o); // string
o = {foo: 'bar'};
console.log(typeof o); // object
I strongly recommend reading the MDN Data Structures docs for more info.
Variable's in JS are untyped manually.
As #DontVoteMeDown mentionned; they are dynamically typed : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
This is your responsibility as a developer to manage your types and control on your JS variables.

Give eval a value in JavaScript

very basic JavaScript programmer here!
I was busy on some code with variables that look like this:
blocktype1;
blocktype2;
blocktype3;
blocktype4;
... //everything between blocktype4 and blocktype70, the three dots are not actual code!
blocktype70;
Now I was using eval() in a function where a value was given to one of the blocktype variables. The blocktype depended on the variable "number".
This is what I had for that part:
eval("blocktype" + number) = 3
What I want is, say "number" is 27, then I want the variable blocktype27 to get a value of 3.
When I check the console it says:
ReferenceError: Invalid left-hand side in assignment
Could anyone possibly help me?
I would prefer just vanilla JavaScript and still the use of eval.
Thank you for your time!
The 'correct' solution would probably be to use an Array which is ideal for sequences and are accessible by index.
var number = 1;
var val = 3;
var blocktype = []; // so clean
blocktype[number] = val;
However, properties can be accessed as with the bracket notation as well. This assumes the variables are in global scope and are thus properties of the global (window) object.
var blocktype1; // .. etc
window["blocktype" + number] = val;
The problem with the eval is that is effectively the same as doing f() = 3 which does not make sense: only variables/properties can be assigned to1.
However eval is a built-in function and the results of a function cannot be assigned to, per the error message. It could be written as
var blocktype1; // .. etc (see dandavis' comment)
eval("blocktype" + number + " = " + val);
// What is actually eval'd is:
// eval("blocktype1 = 3")
which quickly exposes a flaw with eval. If val was the string "Hello world!" with would result in eval("blocktype1 = Hello world!") which is clearly invalid.
1 For the gritty: the left-hand side of an assignment has to be a Reference Specification Type, which is a more wordy way of describining the above behavior. (It is not possible for a JavaScript function to return a RST, although it could technically be done for vendor host objects.)
Feel free not to accept this, since it's specifically not using eval(), but:
You can allocate an array of size 71 like so:
var blocktype = new Array(71);
(your number values apparently start at 1, so we'll have to ignore the first element, blocktype[0], and leave room for blocktype[70], the 71st)
You can now assign elements like this:
blocktype[number] = 3;
and use them like so:
alert( blocktype[number] );

How does Javascript know what type a variable is?

I don't know why I never asked myself that questioned the last years before, but suddenly I could not find any answer for myself or with google.
Javascript is known to have no types for variables. A really nice thing.
But somehow it must determine the type and work with it.
var a = 1;
var b = 2.0;
var c = 'c';
var d = "Hello World!";
So what we have is an Integer, Double/Float, Character, String (which may be teared down as char*)
I know that JS works with a runtime interpreter, but thinking of that the logic and "type" must be implemented in any way..
So how does a Javascript Interpreter recognize and internally handle the variables?
In my imagination, assuming I would write C++, I would think of a sort of template and container and a bit of a logic that overloads operators and try to check, what it really is. But that's not thought to the end.
Share your knowledge with me please :-)
JavaScript sets the variable type based on the value assignment. For example when JavaScript encounters the following code it knows that myVariable should be of type number:
var myVariable = 10;
Similarly, JavaScript will detect in the following example that the variable type is string:
var myVariable = "Hello World!";
JavaScript is also much more flexible than many other programming languages. With languages such as Java a variable must be declared to be a particular type when it is created and once created, the type cannot be changed. This is referred to as strong typing. JavaScript, on the other hand, allows the type of a variable to be changed at any time simply by assigning a value of a different type (better known as loose typing).
The following example is perfectly valid use of a variable in JavaScript. At creation time, the variable is clearly of type number. A later assignment of a string to this variable changes the type from number to string.
var myVariable = 10;
myVariable = "This is now a string type variable";
The variable’s data type is the JavaScript scripting engine’s interpretation of the type of data that variable is currently holding. A string variable holds a string; a number variable holds a number value, and so on. However, unlike many other languages, in JavaScript, the same variable can hold different types of data, all within the same application. This is a concept known by the terms loose typing and dynamic typing, both of which mean that a JavaScript variable can hold different data types at different times depending on context.
Complete article here: http://www.techotopia.com/index.php/JavaScript_Variable_Types
Another Article Which may help you: http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html
Useful links:
ECMAScript Language Specification
ECMAScript BNF Grammar
JAVAScript BNF Gramar
The only useful line I can find in the ES5 spec is this:
Within this specification, the notation “Type(x)” is used as shorthand for “the type of x” where “type” refers to the ECMAScript language and specification types defined in this clause.
I assume that when the runtime needs to perform an operation that needs to know the type of some value, it will check that value against the grammar defined in the spec for each type, until it finds a match.
For example, the grammer for a boolean literal is as follows:
BooleanLiteral ::
true
false
If the value is exactly true or exactly false (e.g. with no quotes) then that value is of type boolean.
JavaScript itself does have types, and internally, each assignment receives an appropriate type. In your example var foo = 2.0; the type will be float. The programmer needn't worry about that too much (at first) because JS is loosly typed (!== type-free). That means that if I were to compare a numeric string to a float, the engine will coerce the string to a number so that the comparison can be preformed.
The main difference between loose typed and strong typed languages is not type coercion, though. It's quite common in C(++) to cast to the type you need, and in some cases values are automatically converted to the correct type (2/2.0 == 2.0/2.0 == 1.0 ==> int is converted to float, implicitly). The main difference between loosly typed and strong typed languages is that you declare a variable with a distinct type:
int i = 0;//ok
//Later:
i = 'a';//<-- cannot assign char to int
whereas JS allows you to do:
var i = 1;//int
i = 1.123;//float
i = 'c';//char, or even strings
i = new Date();//objects
But, as functions/keywords like typeof, instanceof, parseFloat, parseInt,toString... suggest: there are types, they're just a tad more flexible. And variables aren't restricted to a single type.
One simple way to imagine an implementation is that all values are kept in objects and that all variables are pointers... in C++:
struct Value
{
int type;
Value(int type) : type(type) { }
virtual ~Value() { }
virtual std::string toString() = 0;
};
struct String : Value
{
std::string x;
String(const std::string& x) : Value(STRING_TYPE), x(x) { }
virtual std::string toString()
{
return x;
}
};
struct Number : Value
{
double x;
Number(double x) : Value(NUMBER_TYPE), x(x) { }
...
};
struct Object : Value
{
// NOTE: A javascript object is stored as a map from property
// names to Value*, not Value. The key is a string but
// the value can be anything
std::map<std::string, Value *> x;
Object() : Value(OBJECT_TYPE), x(x) { }
...
};
For example whenever an operation has to be performed (e.g. a+b) you need to check the types of the objects pointed by the variables to decide what to do.
Note that this is an ultra-simplistic explanation... javascript today is much more sophisticated and optimized than this, but you should be able to get a rough picture.

To what types do the references get assigned instead of being copied in Javascript?

I am on my mobile phone, so I can't test for myself. Also, I might miss something.
I know that when a number is being assigned, say a = b, b is actually copied into a. But, if b was an object, just a reference wouls be passed. What with other types? Is there something I should worry about?
Also, I heard that you can't use pointers in C# because variables get moved around by the JC. Is it the same in Javascript? How are these references solved in these languages then?
javascript
According to specification, you have types: undefined, null, boolean, string, number, object. You can think of them as immutable except object, which is practically just a (hash)map.
So yes, if you assign variable, it's "copied" (you don't care if it really is) unless it's an object type. Take example:
var x = "hello";
var y = x; //copy or reference, who cares?
x += " world"; //new string object, x references it
alert(y); //alerts hello
C#
According to C# 2.0 specification, there are struct/value types and class/reference types. So, from practical point of view, variable of value type actually stores the data on the call stack (and gets copied on assignment), and variable of reference types is just a reference (and data goes to heap). Example:
int holds_a_value = 5;
StringBuilder holds_a_reference = new StringBuilder();
You can use pointers in C# (pointer = reference), but you have to pin them if you call unsafe functions outside .net / C#, or using unsafe code. e.g.:
fixed (int* p = something) { /*p is safe to use, memory doesn't move */}

Categories