Javascript invalid function? what I am missing? - javascript

I used textwrangler to write my codes to better show my codes and progression. On the comment section of my codes, I wrote my concern and the purpose of my codes.
var pets = ["pet1", "pet2", "pet3"]
function displayPets() {
console.log("my pets:", pets);
}
// addPets() will name all new pets "new pets" ie ("pet1", "pet2", "pet3", "new pets"....)
function addPets() {
pets.push("new pet");
displayPets();
}
/ try different method using the parameter
function addPets(petName) {
pets.push("petName");
displayPets();
}
// pets.push isn't not a function
addPets(brutus)

Will in the different and the first function you are using the same name and you may see another error(not basically error its just a bug) that you can not take the input from the perimeter that is because you are push an string not the variable in the different method and when you are calling the different function you are not putting an string that will also cause an error, If you are not understand hoping the below code can help
var pets = ["pet1", "pet2", "pet3"]
function displayPets() {
console.log("my pets:", pets);
}
// addPets() will name all new pets "new pets" ie ("pet1", "pet2", "pet3", "new pets"....)
function addPets() {
pets.push("new pehttps://stackoverflow.com/questions/44062303/javascript-invalid-function-what-i-am-missing#t");
displayPets();
}
// try different method using the parameter
function addPetsDifferentMethod(petName) {
pets.push(petName);
displayPets();
}
// pets.push isn't not a function
addPetsDifferentMethod("brutes")

There are no overload functions in JS. The last one will alway be called. we have to write the function defeniton to act like Overloaded function.
fiddle
function addPets(petName){
if(petName){ // if petname is present
pets.push(petName)
}
else{
pets.push("newPet");
}
displayPets();
}

Related

How do I make this into a self-invoking function?

I'm not sure how to make this function into a self-invoking function. My code is looping through an array of zip codes from a JS file and sorting it from smallest to biggest and outputting it. I've found online that adding "())" at the end of the newZipCodeArray function, is supposed to self-invoke the function. However, it's not working. What am I doing wrong?
[enter image description here][1]
// Global variable
var zipCodeArray = [];
(function newZipCodeArray(currentZipCode) {
var valueFound = false;
for (zipCodeIndex = 0; zipCodeIndex <= zipCodeArray.length; zipCodeIndex++) {
if (currentZipCode === zipCodeArray[zipCodeIndex]) {
valueFound = true;
}
}
if (valueFound === false) {
zipCodeArray.push(currentZipCode);
}
}());
function newZipCodeArrayssignment12_3() {
// Instantiate variables.
var output;
var zipCodeRecords;
// Get the element.
output = document.getElementById('outputDiv');
zipCodeRecords = openZipCodeStudyRecordSet();
// Call the function to read the next record.
while (zipCodeRecords.readNextRecord()) {
currentZipCode = zipCodeRecords.getSampleZipCode();
newZipCodeArray(currentZipCode);
}
// Sort the zip code array.
zipCodeArray.sort();
}
The syntax involved in immediately-invoked (or self-invoked) functions doesn't allow it to be invoked from elsewhere. The IIFE pattern is intended to be used when the function only needs to be invoked once.
Note:
The grouping parenthesis wrapping the function change it from a declaration to an expression. And, as an expression, its name won't be added to the surrounding scope for other code to reference.
To invoke newZipCodeArray once right away and allow for it again later, you'll want to remove the parenthesis from around it and call it by name in a separate statement:
newZipCodeArray(); // first call
function newZipCodeArray(currentZipCode) {
// ...
}
function newZipCodeArrayssignment12_3() {
// ...
while (zipCodeRecords.readNextRecord()) {
// ...
newZipCodeArray(currentZipCode); // additional calls
}
// ...
}

how to get a property name which represent a function in JS

This is some JS code
var methodArr = ['firstFunc','secondFunc','thirdFunc'];
for(var i in methodArr)
{
window[methodName] = function()
{
console.log(methodName);
}
}
My problem is that how to get the name of a function in JS.
In JS, use this.callee.name.toString() can get the function name. But in this situation, it is a null value. How can i get the 'funName' string?
Sorry, I didn't make it clear.
I want to create functions in a for loop, all these functions has almost the same implementation which need its name. But others can call these functions use different name.I want to know what methodName function is called.
it seems a scope problem.
Try this:
var methodArr = ['firstFunc','secondFunc','thirdFunc'];
for(var i in methodArr) {
var methodName = methodArr[i]; // <---- this line missed in your code?
window[methodName] = (function(methodName) {
return function() {
console.log(methodName);
}
})(methodName);
}
window['secondFunc'](); // output: secondFunc

How to get input from Chrome's Javascript console?

Is there a way to programmatically get input from the Javascript Console of Google Chrome, similar to readline() in Firefox?
A tricky way to do this is assigning a getter to a property of a window object
Object.defineProperty(window, 'customCommand', {
get: function() {
console.log("hey");
return "hey";
}
});
So when you type "customCommand" (without parenthesis) it will print your console.log text to the console while the console is "getting" the variable.
You will still have to return something though, and I'm not sure how you could change the order so that the value is returned first and the text in the console appears second. It's definitely possible though, I've seen this happen.
This is an indirect method of taking inputs:
Declare a function in JavaScript:
function your_command_here() {
//code
}
As Chrome's console basically provides methods for communicating with the page's contents, like JavaScript variables, functions, etc., so declaring a function as a receivable command can be an option.
In the console, for providing input, the user shall type:
your_command_here()
Another workaround is:
Declare a function:
function command(var cmnd) {
switch(cmnd) {
case "command1":
//code
break;
}
}
So the user can (more conveniently) type:
command("user's command here")
We can do is hook the console.log so whenever it logs something we can access, otherwise there is no such direct method as like in firefox which does this possible for us in a simple single line code.
var tempStore = [];
var oldLog = console.log;
console.log = function() {
tempStore.push(arguments);
oldLog.apply(console, arguments);
}
You might need to incorporate jsh (Javascript Shell) in your environment if you are working with console IO. See http://code.google.com/p/jsh/ for the how-to. Hope this helps.
Sorry, doesn't work on Chrome JS Console, just works on the repl from repl.it
Example from repl.it:
console.log("Enter your name:");
console.read(function(name) {
console.log('Your name is ' + name + '.');
});
Here is a solution to input from the console.
Try this out!!
process.stdin.resume();
process.stdin.setEncoding('ascii');
var stdInput = "";
var stdInputArr = "";
var index = 0;
process.stdin.on('data', function (data) {
stdInput += data;
});
process.stdin.on('end', function () {
stdInputArr = stdInput.split("\n");
main();
});
// Reads complete line from STDIN
function readLine() {
return stdInputArr[index++];
}
//call this function in the main function
javascript node.js jquery consoleweb
The better you can do is use:
myVar = prompt('Which value do your want?')

unexpected call to a function in Javascript

I'm not really good at javascript so I'm here asking.
Below is a sample code.
<html>
<head>
<script>
function test(one)
{
alert('surprise! first function with one parameter');
}
function test(one,two)
{
alert('expected: second function with two parameters');
}
</script>
</head>
<body onload="javascript:test('first')">
</body>
</html>
Questions:
I expected that that 'surprise! first function with one parameter' would be then alerted onload because I call the function with one parameter only. To my surprise it alerted in the second function.
Can someone explain this to me why?
and how can I make my way around it?
Javascript doesn't support method overloading;
It just overwrites the function so the last one will get called every time.
A way around it is just to make 1 function and put some conditions in there to check if the variables are set.
You declare twice the function test. The 2nd one overwrite the first definition.
In JavaScript overloaded functions are not allowed. so in this case the second function overrides the first one and therefore you always see this result.
A work around for this is to check the values of the parameters:
function test(one,two)
{
if(two)
alert('expected: second function with two parameters');
else
alert('surprise! first function with one parameter');
}
In javascript the parameters for a function aren't required. You'd want to check to see if the parameter is undefined before using it.
If used this before in order to implement getter/setter type functionality in javascript similar to below:
var _pageSize;
function pageSize(value) {
if (value) {
_pageSize = value;
}
else {
return _pageSize;
}
}
You can then use the pageSize method to both get and set the page size like below:
if (pageSize() < 15) {
pageSize(15)
}
Ah, Javascript doesn't do polymorphism like that. It does have an arguments collection that you can look in and then do the right thing given the inputs..
stuff like:
function calcAverage()
{
var sum = 0
for(var i=0; i<arguments.length; i++)
sum = sum + arguments[i]
var average = sum/arguments.length
return average
}
document.write("Average = " + calcAverage(400, 600, 83))
When calling such function:
function test(one,two)
With only one parameter, the argument "two" will have special type: undefined.
Any attempt to access the variable two will fail with "two is undefined" error, to avoid such error use the typeof command:
function test(one,two)
{
if (typeof two == "undefined") {
//give default value
two = "default value here";
}
...
}

How can I get the name of function inside a JavaScript function?

How is it possible to learn the name of function I am in?
The below code alerts 'Object'. But I need to know how to alert "Outer."
function Outer(){
alert(typeof this);
}
This will work:
function test() {
var z = arguments.callee.name;
console.log(z);
}
I think that you can do that :
var name = arguments.callee.toString();
For more information on this, take a look at this article.
function callTaker(a,b,c,d,e){
// arguments properties
console.log(arguments);
console.log(arguments.length);
console.log(arguments.callee);
console.log(arguments[1]);
// Function properties
console.log(callTaker.length);
console.log(callTaker.caller);
console.log(arguments.callee.caller);
console.log(arguments.callee.caller.caller);
console.log(callTaker.name);
console.log(callTaker.constructor);
}
function callMaker(){
callTaker("foo","bar",this,document);
}
function init(){
callMaker();
}
As of ES6, you can use Function.prototype.name. This has the added benefit of working with arrow functions, since they do not have their own arguments object.
function logFuncName() {
console.log(logFuncName.name);
}
const logFuncName2 = () => {
console.log(logFuncName2.name);
};
Took me a while to figure this out, so tried to make it very clear for rookies like me.
Approach 1 - arguments.callee.name
This approach used to work, but now in ES6 Strict Mode it will fail. Don't use Approach 1.
//approach 1 - don't use
let functionName = arguments.callee.name;
console.log(functionName);
Approach 2 - create a function and use caller.name
This approach works in the latest version of Javascript and will not fail in Strict Mode. Use Approach 2. There are 2 steps.
Step 1 - Create a function that uses caller.name to return the name of the function that called it. Add this function to your code:
function getFuncName() {
return getFuncName.caller.name
}
Step 2 - Call your function when you need the name of the function your code is currently in.
function iWantThisName() {
console.log(getFuncName())
}
iWantThisName()
// Logs: "iWantThisName"

Categories

Resources