👨🏼‍💻

khriztianmoreno's Blog

Home Tags About |

Posts with tag programming

Predictions 🧞‍♀️💻 2024

2023-12-04
programmingweb-developmentdiscuss

Some points you should pay attention to for this year 2024 that will surely have a high impact on the technological ecosystem.Bun achieves its goal of becoming the default frontend runtime: They still have some hurdles to overcome, but if they manage to provide a drop-in replacement for Node that instantly improves your application's performance 10x, it will be an obvious choice for most developers. The v1.0 release last September was a major step towards overall Windows compatibility and stability, and the bet is that Bun will start becoming the default choice this year.AI will replace no-code/low-code tools: It turns out that AI is much better and faster at creating marketing analytics dashboards. Tools like Basedash and 8base already use AI to create a full set of requirements, custom internal tools, and others will emerge to replace drag-and-drop builders to create sites that don't rely heavily on business logic.Netlify is acquired by GoDaddy: With multiple rounds of layoffs, 2023 was clearly not the best year for Netlify. But sometimes the best way to recover is to find a new ~~sugar daddy~~, GoDaddy. After retiring the Media Temple brand a few months ago, it looks like GoDaddy might be back in the acquisition market for a platform like Netlify.Any other ones you can think of? Help me update this post!!Profile@khriztianmoren

Clone an Object in JavaScript - 4 Best Ways

2023-06-18
javascriptprogrammingweb-development

Cloning an object in JavaScript means creating an identical copy of an existing object. This means that the new object will have the same values ​​for each property, but it will be a different object.Why is it important to clone an object in javascript?Cloning an object in javascript is important to preserve the original state of an object and prevent the propagation of changes. This is especially useful when there are multiple instances of an object that are shared between various parts of the application. Cloning the original object ensures that the other instances are not affected by changes made to the original object. This also allows developers to use a single instance of the object and create a unique copy for each part of the application. This avoids having to create a new instance of the object every time, saving time and resources.How to clone an object?To clone a JavaScript object correctly, you have 4 different options:Use the structuredClone() functionUse the spread operatorCall the Object.assign() functionUse JSON parsing.const data = { name: "khriztianmoreno", age: 33 }; // 1 const copy4 = structuredClone(data); // 2 const copy1 = { ...data }; // 3 const copy2 = Object.assign({}, data); // 4 const copy3 = JSON.parse(JSON.stringify(data));1. structuredClone()Creates a deep clone of a given value using the structured cloning algorithm.const original = { someProp: "with a string value", anotherProp: { withAnotherProp: 1, andAnotherProp: true, }, }; const myDeepCopy = structuredClone(original);2. spread operatorThe spread operator (...) allows you to spread an object or array into a list of individual elements, and is used to create a copy of an object.const original = { name: "khriztianmoreno", age: 33 }; const clone = { ...original };In the above example, a new clone object is being created from the values ​​of the original object, it is important to note that this only makes a shallow copy, if the original object contains objects or arrays within it, these will not be cloned but the reference of the original object will be assigned.It can also be used to clone arrays as follows:const original = [1, 2, 3, 4]; const clone = [...original];3. Object.assignThe Object.assign() function is another way to clone objects in JavaScript. The function takes a target object as its first argument, and one or more source objects as additional arguments. It copies enumerable properties from the source objects to the target object.const original = { name: "khriztianmoreno", age: 33 }; const clone = Object.assign({}, original);4. JSON parsingThe JSON.parse() and JSON.stringify() methods are another way to clone objects in JavaScript. The JSON.stringify() method converts an object into a JSON string, while the JSON.parse() method converts a JSON string into a JavaScript object.const original = { name: "khriztianmoreno", age: 33 }; const clone = JSON.parse(JSON.stringify(original));ConclusionsAdvantages of cloning an object in javascriptObject cloning allows the developer to create a copy of an existing object without having to redefine all the values ​​of the object. This means that the developer can save time and effort by not having to recreate an object from scratch.Object cloning also allows the developer to create a modified version of an existing object. For example, a developer can modify the values ​​of an existing object to create a customized version. This is useful in saving time by not having to rewrite the code to create an object from scratch.Object cloning also allows the developer to create an improved version of an existing object. For example, a developer can add new properties to an existing object to improve its functionality.Object cloning also offers a way to backup objects. This means that if the existing object is affected by a software failure, the developer can resort to the backup to recover the original values.Disadvantages of cloning an object in javascriptCloning an object in Javascript can be a useful task, but there are also some drawbacks that need to be considered. The first is the execution time. Cloning objects in Javascript can be a slow process, especially if the object is large. This can lead to a poor user experience if you are trying to clone an object while running an application.Another disadvantage of cloning objects in Javascript is that you cannot clone complex objects. This means that objects that contain references to other objects cannot be cloned properly. This can be a problem if you are trying to clone an object that contains references to other important objects, as the clone will not have these references.Lastly, cloning objects in Javascript can also lead to security issues if you clone objects that contain sensitive information. The clone can contain the same information as the original object, which can be a security risk if you share the clone with other users.That's all folks! I hope this article helps you understand the different options we have when it comes to cloning an object/array in javascript.Profile@khriztianmorenoPS: This article was written entirely using Artificial Intelligenc

How to use Call, Apply and Bind methods in javascript

2023-05-12
javascriptweb-developmentprogramming

In this article, we'll look at what call, apply, and bind methods are in javascript and why they exist.Before we jump in, we need to know what this is in javascript, in this post you can go a little deeper.Call, Apply and BindIn Javascript, all functions will have access to a special keyword called this, the value of this will point to the object on which that function is executed.What are these call, apply and bind methods?To put it in a simple way, all these methods are used to change the value of this inside a function.Let us understand each method in detail.call()Using the call method, we can invoke a function, passing a value that will be treated as this within it.const obj = { myName: "khriztianmoreno", printName: function () { console.log(this.myName); }, }; obj.printName(); // khriztianmoreno const newObj = { myName: "mafeserna", }; obj.printName.call(newObj); //mafesernaIn the above example, we are invoking the call method in the printName function by passing newObj as a parameter, so now this inside printName points to newObj, hence this.myName prints mafeserna.How to pass arguments to functions?The first argument of the call method is the value pointed to by this inside the function, to pass additional arguments to that function, we can start passing it from the second argument of the call method.function foo(param1, param2) {} foo.call(thisObj, arg1, arg2);where:foo is the function we are calling by passing the new this value which is thisObjarg1, arg2 are the additional arguments that the foo function will take ( param1= arg1 , param2 = arg2 )apply()The apply function is very similar to the call function. The only difference between call and apply is the difference in how the arguments are passed.call — we pass arguments as individual values, starting from the second argumentapply — additional arguments will be passed as an arrayfunction sayHello(greet, msg) { console.log(`${greet} ${this.name} ! ${msg}`); } const obj = { name: "khriztianmoreno", }; // Call sayHello.call(obj, "Hello", "Good Morning"); // Hello khriztianmoreno ! Good Morning // Apply sayHello.apply(obj, ["Hello", "Good Morning"]); // Hello khriztianmoreno ! Good MorningIn the above example, both the call and apply methods in the sayHello function are doing the same thing, the only difference is how we are passing additional arguments.bind()Unlike the call and apply methods, bind will not invoke the function directly, but will change the this value inside the function and return the modified function instance.We can invoke the returned function later.function sayHello() { console.log(this.name); } const obj = { name: "khriztianmoreno" }; // it won't invoke, it just returns back the new function instance const newFunc = sayHello.bind(obj); newFunc(); // khriztianmorenopassing additional arguments: Passing additional arguments in bind works similarly to the call method, we can pass additional arguments as individual values ​​starting from the second argument of the bind method.function sayHello(greet) { console.log(`${greet} ${this.name}`); } const obj = { name: "khriztianmoreno" }; const newFunc = sayHello.bind(obj, "Hello"); newFunc(); // Hello khriztianmorenoIn case of bind method, we can pass additional arguments in two ways:While calling the bind method itself, we can pass additional arguments along with the value of this to that function.Another way is that we can pass additional arguments while invoking the return function of the bind method.We can follow any of the above ways and it works similarly without any difference in functionality.function sayHello(greet) { console.log(`${greet} ${this.name}`); } const obj = { name: "khriztianmoreno" }; const newFunc1 = sayHello.bind(obj, "Hello"); newFunc1(); // Hello khriztianmoreno const newFunc2 = sayHello.bind(obj); newFunc2("Hello"); // Hello khriztianmorenoNOTE: if we don't pass any value or we pass null while calling call, apply, bind methods, then this inner calling function will point to the global object.function sayHello() { // executing in browser env console.log(this === window); } sayHello.call(null); // true sayHello.apply(); // true sayHello.bind()(); // trueWe cannot use call, apply and bind methods in arrow functions to change the value of this, because arrow functions do not have their own this context.The this inside the arrow function will point to the outer/parent function in which it is present.Therefore, applying these methods in the arrow function will have no effect.That's all folks! I hope this article helped you understand what call(), apply() and bind() methods are in javascript!Profile@khriztianmoren

Introduction to .env files

2023-03-09
javascriptweb-developmentprogramming

Imagine having to pay nearly $148 million for a data breach that exposed the data of some 57 million users 😱😰Well, that's what happened to Uber, not long ago, and the culprit was none other than a coded secret published openly for any bad actor to exploit.That's why in this post, we're going to learn what they are and how we could work them into our projects with javascript.envContextToday, millions of software developers keep their secrets (i.e. credentials such as access keys and tokens to services used by programs) safe with .env files.For those unfamiliar with the topic, .env files were introduced in 2012 as part of a solution to the hard-coded secret problem mentioned in the introductory paragraph above.Instead of sending secrets along with their codebase to the cloud, developers could now send their codebase to the cloud and keep their secrets separated on their machines in key-value format in .env files; this separation reduced the risk of bad actors getting their hands on sensitive credentials in the cloud.To run programs, developers would now just need to pull their latest codebase from the remote repository and inject the secrets contained in their local .env files into the pulled code.Unless a development team is small and "skeletal" and doesn't care much about DevOps, it typically maintains multiple "environments" for its codebase to ensure that changes are well tested before being pushed to production to interact with end users. In the case of multiple environments, developers may choose to employ multiple .env files to store credentials, one for each of those environments (for example, one .env file to hold development database keys and another to hold production database keys).To summarize, .env files contain credentials in key-value format for the services used by the program they are building. They are meant to be stored locally and not uploaded to online code repositories for everyone to read. Each developer on a team typically maintains one or more .env files for each environment.UsageIn this post, we'll look at how to use a .env file in a basic project, assuming you're using Node.js and git for version control; this should apply to other languages ​​as well. Feel free to skip this section if you're not interested in the technicalities of how to use a .env file.To get started, head to the root of your project folder and create an empty .env file containing the credentials you'd like to inject into your codebase. It might look something like this:SECRET_1=924a137562fc4833be60250e8d7c1568 SECRET_2=cb5000d27c3047e59350cc751ec3f0c6Next, you'll want to ignore the .env file so that it doesn't get committed to git. If you haven't already, create a .gitignore file. It should look something like this:.envNow, to inject the secrets into your project, you can use a popular module like dotenv; it will parse the .env file and make your secrets accessible within your codebase under the process object. Go ahead and install the module:npm install dotenvImport the module at the top of the startup script for your codebase:require(‘dotenv’).config()That's it, you can now access secrets anywhere in your codebase:// display the value of SECRET_1 into your code console.log(process.env.SECRET_1); // -> 924a137562fc4833be60250e8d7c1568 // display the value of SECRET_2 into your code console.log(process.env.SECRET_2); // -> cb5000d27c3047e59350cc751ec3f0c6Excelente. Ha agregado con éxito un archivo .env a su proyecto con algunos secretos y ha accedido a esos secretos en su base de código. Además, cuando envías tu código a través de git, tus secretos permanecerán en tu máquina.ChallengesWhile simple and powerful, .env files can be problematic when managed incorrectly in the context of a larger team.Imagine having to distribute and track hundreds of keys to your software development team.On a simplified level, between Developer_1 and Developer_2, here's what could happen:Developer_1 could add an API key to their local .env file and forget to tell Developer_2 to add it to theirs - this cost Developer_2 15 minutes down the road debugging why their code is crashing only to realize it's because of the missing API key.Developer_2 could ask Developer_1 to send them the API key so they can add it to their .env file, after which Developer_1 can choose to send it via text or email - this cost Developer_2 15 minutes down the road debugging why their code is crashing only to realize it's because of the missing API key.This now unnecessarily puts your organization at risk of bad actors like Developer_2 waiting precisely to intercept the API key.Unfortunately, these challenges are common and even have a name: secret sprawl.Over the past few years, many companies have attempted to solve this problem. HashiCorp Vault is a product that securely stores secrets for large enterprises; however, it is too expensive, cumbersome, and downright overkill to set up for the average developer who just needs a fast and secure way to store these secrets.Simpler solutions exist, such as Doppler and the new dotenv-vault, but they often lack the security infrastructure needed to gain mass adoption.Let me know in the comments what tools or services you use to easily and safely solve secret sprawl.That's all folks! I hope this helps you become a better dev!Profile@khriztianmoreno �

Some methods beyond console.log in Javascript

2023-02-17
javascriptweb-developmentprogramming

Some methods beyond console.log in JavascriptOften, during debugging, JavaScript developers tend to use the console.log() method to print values. But there are some other console methods that make life much easier. Want to know what these methods are? Let's get to know them!1. console.table()Displaying long arrays or objects is a headache using the console.log() method, but with console.table() we have a much more elegant way to do it.// Matrix const matrix = [ ["apple", "banana", "cherry"], ["Rs 80/kg", "Rs 100/kg", "Rs 120/kg"], ["5 ⭐", "4 ⭐", "4.5 ⭐"], ]; console.table(matrix); // Maps class Person { constructor(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } } const family = {}; family.mother = new Person("Jane", "Smith"); family.father = new Person("John", "Smith"); family.daughter = new Person("Emily", "Smith"); console.table(family);console.table()2. console.trace()Having trouble debugging a function? Wondering how the execution flows? console.trace() is your friend!function outerFunction() { function innerFunction() { console.trace(); } innerFunction(); } outerFunction();console.trace()3. console.error() and console.warn()Tired of boring logs? Spice things up with console.error() and console.warn()console.error("This is an error message"); console.warn("This is a warning message"); console.log("This is a log message");console.error()4. console.assert()This is another brilliant debugging tool! If the assertion fails, the console will print the trace.function func() { const a = -1; console.assert(a === -1, "a is not equal to -1"); console.assert(a >= 0, "a is negative"); } func();console.assert()5. console.time(), console.timeEnd(), and console.timeLog()Need to check how long something is taking? Timer methods are there to rescue you!console.time("timeout-timer"); setTimeout(() => { console.timeEnd("timeout-timer"); }, 1000); setTimeout(() => { console.timeLog("timeout-timer"); }, 500);console.time()NOTE: setTimeouts are not executed immediately, which results in a slight deviation from the expected time.That's all folks! I hope this helps you become a better dev!Profile@khriztianmoreno on Twitter and GitHu

Introduction to Volta, the fastest way to manage Node environments

2022-05-27
javascriptweb-developmentprogramming

Volta is a tool that opens up the possibilities for a smoother development experience with Node.js. This is especially relevant for working in teams. Volta allows you to automate your Node.js development environment. It allows your team to use the same consistent versions of Node and other dependencies. Even better, it allows you to keep versions consistent across production and development environments, eliminating the subtle bugs that come with version mismatches.Volta eliminates “It works on my machine...” problems.Version mismatches cause headaches when developing in teams.Let's assume this scenario:Team X built their application on local machines running Node 10, but the build pipeline defaulted to the lowest version of Node they had on hand, Node 6, and the application would not start in production. They had to revert the deployment, figure out what went wrong, it turned into a very long night.If they had used Volta this could have been avoided.How does Volta work?Volta is “a simple way to manage your JavaScript command line tools”. It makes managing Node, npm, yarn or other JavaScript executables shipped as part of packages really easy.Volta has a lot in common with tools like NVM, but NVM is not the easiest to set up initially and, more importantly, the developer using it still has to remember to switch to the correct version of Node for the project they are working on.Volta, on the other hand, is easy to install and takes the thinking part out of the equation: once Volta is configured in a project and installed on a local machine, it will automatically switch to the appropriate versions of Node.Not only that, but it will also allow you to define yarn and npm versions in a project, and if the version of Node defined in a project is not downloaded locally, Volta will go out and download the appropriate version.But when you switch to another project, Volta will either fall back to the presets in that project or revert to the default environment variables.Volta in actionLet's give Volta a spin. First, create a new React application with Create React App.Run the following command from a terminal.npx create-react-app volta-sample-appOnce you have created your new React application, open the code in an IDE and start it through the command line.npm run startIf all goes according to plan, you will see a rotating React logo when you open a browser at http://localhost:3000/.Now that we have an application, let's add Volta.Download Volta locallyTo install Volta, run the following command:curl https://get.volta.sh | shellIf you have Windows, download and run the Windows installer and follow the instructions.Define your environment variablesBefore we add our Volta-specific versions of Node and npm to our project, let's see what the default environment variables are.Get a reference readingIn a terminal at the root of your project, run the following command.node -v && npm -vFor me, my default versions of Node and npm are v14.18.1 and v6.14.15, respectively.With our baseline set, we can change our versions just for this project with the help of Volta.Setting a node.js versionWe'll start with Node. Since v16 is the current version of Node, let's add that to our project.In our project at the root level where our package.json file lives, run the following command.volta pin node@16Using volta pin [JS_TOOL]@[VERSION] will put this particular JavaScript tool in our version specified in our application's package.json. After committing this to our repository with git, any future developer using Volta to manage dependencies will be able to read this from the repository and use the exact same version.With Volta we can be as specific or generic as we want to define the versions, and Volta will fill in any gaps. I specified the major version of Node that I wanted (16) and then Volta filled in the minor and patch versions for me.After pinning, you will see the following success message on your terminal: pinned node@16.11.1 in package.json..Tip: make your version of node pinned to match the version of Node on your build serverSetting an npm versionNow let's tackle our npm version. Still in the root of our project in the terminal, run this command:volta pin npmWithout a version specified, Volta defaults to the latest LTS version to add to our project.The current LTS version for npm is 8, so now our project has npm v8.1.0 as its default version.Verify the package.json.To confirm that the new versions of the JavaScript environment are part of our project, check the package.json file of the application.Scroll down and you should see a new property named “volta”. Inside the “volta” property there should be a “node”: “16.11.1” and an “npm”: “8.1.0” version.From now on, any developer who has Volta installed on their machine and downloads this repository will have the configuration of these tools to automatically switch to use these particular versions of node and npm.To be doubly sure, you can also re-run the first command we did before anchoring our versions with Volta to see how our current development environment is configured.node -v && npm -vAfter that, your terminal should tell you that you are using those same versions: Node.js v16 and npm v8.Watch the magic happenNow, you can sit back and let Volta take care of things for you.If you want to see what happens when nothing is specified for Volta, try going up one level from the root of your project and check your Node and npm versions again.Let's open two terminals side by side: the first one inside our project with Volta versions, the other one level higher in our folder structure.Now run the following command in both of them:node -v && npm -vAnd in our project, Node v16 and npm v8 are running, but outside the project, Node v14 and npm v6 are present. We did nothing more than change directories and Volta took care of the rest.By using Volta, we took the guesswork out of our JavaScript environment variables and actually made it harder for a member of the development team to use the wrong versions than the right ones.Profile@khriztianmoren

Predictions 🧞‍♀️💻 2022

2022-01-04
programmingweb-developmentdiscuss

Some points you should pay attention to for this year 2022 that will surely have a high impact on the technology ecosystem.RIP Babel and Webpack: They will not disappear forever, but will be largely replaced by new compiler tools that are faster and more intuitive, such as SWC, esbuild and Vite.Serverless will help frontend developers become (real) fullstack developers: and (hopefully) get paid accordingly. Much of the serverless technology is based on V8 and is adopting Web APIs, so frontend developers will already be familiar with the key parts of the serverless infrastructure. Now, instead of starting up an Express server and calling yourself a “fullstack developer”, Serverless will allow you to actually be one.Next.js will become less of a React meta-framework and more of a web meta-framework: Vercel has already hired Rich Harris (aka Lord of the Svelte) and has shared their plans for an edge-first approach to the web with any framework. They will lean even more on this in 2022, adapt to more JS frameworks/libs (with pillowcases full of cash) and prepare for an IPO.No/Low-code tools will dominate even more: We will probably continue to ignore them; meanwhile, more agencies and teenagers will make millions of dollars submitting sites without writing a line of code. In 2022, we'll also start to see more established software companies with “real developers” leveraging no-code or low-code tools because the best code is the code you don't have to maintain.Meta will cede control of React: Just like when they created GraphQL Foundation in 2018, Meta will create a React Foundation later this year and cede control of React. Unlike Microsoft/Amazon/Google, Meta has never (successfully) monetized developers, so React is not a strategic priority for the company. That might be even more true now, with Zuck's eyes on Metaverse and Sebastian Markbåge leaving for Vercel.VC will solve Open Source funding: At least, it will feel that way. With some pre-revenue/traction/pmf OSS projects generating seed rounds at valuations between $25-50MM, you'll want to dust off that old side project of yours. I don't know if it's sustainable (it's not), but it's a lot better than when we relied on Patreon to fund our critical web infrastructure.Netlify to acquire Remix: Bottoms up framework is the wave. Netlify will want the distribution and Remix will want the... money. It would allow the Remix team to spend their time on what they are good at, Remix-the-framework, rather than Remix-the-business. The pairing would give them both a much better chance of catching up with Vercel/Next.js.While all that is going on ...? we can continue to work quietly.Profile@khriztianmoren